#include "mainwindow.h"
#include <iostream>

MainWindow::MainWindow( QString default_font_str_arg )
{
blocking = 0;

appTranslator = NULL;
qtTranslator = NULL;
setupUi(this);

lang = QLatin1String("en");

default_font_str = default_font_str_arg;

originalPalette = QApplication::palette();
itemTabWidget->setDisabled(true);

readSettings();

db_root = QCoreApplication::applicationDirPath();
db_name = QLatin1String("");
db_user = QLatin1String("");
db_passwd = QLatin1String("");
buildin_db = false;
db_opened = false;

opened_album = QLatin1String("");
opened_album_num = QLatin1String("");
opened_album_name = QLatin1String("");
number_of_collections = -1;

images_data_set = false;
documents_data_set = false;
other_data_set = false;
geo_data_set = false;
auctions_data_set = false;
catalogs_data_set = false;
desc_data_set = false;
icons_data_set = false;

gl_tested = false;
max_size = 0;

last_im_dir = QLatin1String("");
last_doc_dir = QLatin1String("");
last_image_save_dir = QLatin1String("");
last_exp_save_dir  = QLatin1String("");

m0 = new QMovie(":/binary/save_desc.gif");
m1 = new QMovie(":/binary/arrow.gif");

update_actions(true);

iconObvLabel->addAction(actionFullObv);
iconRevLabel->addAction(actionFullRev);
iconEdgeLabel->addAction(actionFullEdge);

// temp disabled
actionContacts->setDisabled(true);
actionPrintRM->setDisabled(true);
actionPricelist->setDisabled(true);
actionReport->setDisabled(true);
//actionZh->setDisabled(true);
actionGerman->setDisabled(true);
actionExportNUDS->setDisabled(true);
actionImportNUDS->setDisabled(true);
actionImpSQLITE->setDisabled(true);
actionExpSQLITE->setDisabled(true);
actionGerman->setCheckable(true);
actionRussian->setCheckable(true);
//actionZh->setCheckable(true);
actionEnglish->setCheckable(true);

tableView->addAction(actionEditRM);
tableView->addAction(actionPrintRM);
tableView->addAction(actionCopyRM);
tableView->addAction(actionDeleteRM);
tableView->addAction(actionUpdateRM);

catTableView->addAction(actionCatN);
catTableView->addAction(actionCatE);
catTableView->addAction(actionCatD);

auctTableView->addAction(actionAuctN);
auctTableView->addAction(actionAuctE);
auctTableView->addAction(actionAuctD);

geoTableView->addAction(actionGeoN);
geoTableView->addAction(actionGeoE);
geoTableView->addAction(actionGeoD);

otherTableView->addAction(actionOtherN);
otherTableView->addAction(actionOtherE);
otherTableView->addAction(actionOtherD);

imagesTableView->addAction(actionImage);
imagesTableView->addAction(actionImN);
imagesTableView->addAction(actionImD);
imagesTableView->addAction(actionObvI);
imagesTableView->addAction(actionRevI);
imagesTableView->addAction(actionEdgeI);
imagesTableView->addAction(actionSaveAs);
imagesTableView->addAction(actionClipboard);

docsTableView->addAction(actionDocN);
docsTableView->addAction(actionDocD);
docsTableView->addAction(actionSaveDoc);

view_index = QModelIndex();
view_record = QSqlRecord();

filter_ = QLatin1String("");

QPixmapCache::setCacheLimit(20480);

// strings
SchemaViewItem i_nominal;
i_nominal.field = QLatin1String("DENOMINATION");
i_nominal.label_p = nominalLabel;
i_nominal.lineEdit_p = nominalLineEdit;
list_string_view_items.push_back(i_nominal);

SchemaViewItem i_state;
i_state.field = QLatin1String("STATE");
i_state.label_p = stateLabel;
i_state.lineEdit_p = stateLineEdit;
list_string_view_items.push_back(i_state);

SchemaViewItem i_epoch;
i_epoch.field = QLatin1String("EPOCH");
i_epoch.label_p = epochLabel;
i_epoch.lineEdit_p = epochLineEdit;
list_string_view_items.push_back(i_epoch);

SchemaViewItem i_marks;
i_marks.field = QLatin1String("MARKS");
i_marks.label_p = marksLabel;
i_marks.lineEdit_p = marksLineEdit;
list_string_view_items.push_back(i_marks);

SchemaViewItem i_edge;
i_edge.field = QLatin1String("EDGE");
i_edge.label_p = edgeLabel;
i_edge.lineEdit_p = edgeLineEdit;
list_string_view_items.push_back(i_edge);

SchemaViewItem i_material;
i_material.field = QLatin1String("MATERIAL");
i_material.label_p = materialLabel;
i_material.lineEdit_p = materialLineEdit;
list_string_view_items.push_back(i_material);

SchemaViewItem i_cond;
i_cond.field = QLatin1String("CONDITION");
i_cond.label_p = condLabel;
i_cond.lineEdit_p = condLineEdit;
list_string_view_items.push_back(i_cond);

SchemaViewItem i_cert;
i_cert.field = QLatin1String("CERT_AUTH");
i_cert.label_p = NULL;
i_cert.lineEdit_p = certLineEdit;
list_string_view_items.push_back(i_cert);

SchemaViewItem i_condNote;
i_condNote.field = QLatin1String("COND_NOTE");
i_condNote.label_p = NULL;
i_condNote.lineEdit_p = condNoteLineEdit;
list_string_view_items.push_back(i_condNote);

SchemaViewItem i_axis1;
i_axis1.field = QLatin1String("AXIS1");
i_axis1.label_p = axis1Label;
i_axis1.lineEdit_p = axis1LineEdit;
list_string_view_items.push_back(i_axis1);

SchemaViewItem i_axis2;
i_axis2.field = QLatin1String("AXIS2");
i_axis2.label_p = axis2Label;
i_axis2.lineEdit_p = axis2LineEdit;
list_string_view_items.push_back(i_axis2);

SchemaViewItem i_shape;
i_shape.field = QLatin1String("SHAPE");
i_shape.label_p = shapeLabel;
i_shape.lineEdit_p = shapeLineEdit;
list_string_view_items.push_back(i_shape);

SchemaViewItem i_edgeID;
i_edgeID.field = QLatin1String("EDGEID");
i_edgeID.label_p = edgeIDLabel;
i_edgeID.lineEdit_p = edgeIDLineEdit;
list_string_view_items.push_back(i_edgeID);

SchemaViewItem i_type;
i_type.field = QLatin1String("OBJ_TYPE");
i_type.label_p = typeLabel;
i_type.lineEdit_p = typeLineEdit;
list_string_view_items.push_back(i_type);

SchemaViewItem i_undertype;
i_undertype.field = QLatin1String("OBJ_UNDERTYPE");
i_undertype.label_p = undertypeLabel;
i_undertype.lineEdit_p = undertypeLineEdit;
list_string_view_items.push_back(i_undertype);

SchemaViewItem i_edgeLegend;
i_edgeLegend.field = QLatin1String("EDGE_LEGEND");
i_edgeLegend.label_p = NULL;
i_edgeLegend.lineEdit_p = edgeLegendLineEdit;
list_string_view_items.push_back(i_edgeLegend);

SchemaViewItem i_artistObv;
i_artistObv.field = QLatin1String("OBVERSEARTIST");
i_artistObv.label_p = artistObvLabel;
i_artistObv.lineEdit_p = artistObvLineEdit;
list_string_view_items.push_back(i_artistObv);

SchemaViewItem i_artistRev;
i_artistRev.field = QLatin1String("REVERSEARTIST");
i_artistRev.label_p = artistRevLabel;
i_artistRev.lineEdit_p = artistRevLineEdit;
list_string_view_items.push_back(i_artistRev);

SchemaViewItem i_engraverObv;
i_engraverObv.field = QLatin1String("OBVERSEENGRAVER");
i_engraverObv.label_p = engraverObvLabel;
i_engraverObv.lineEdit_p = engraverObvLineEdit;
list_string_view_items.push_back(i_engraverObv);

SchemaViewItem i_engraverRev;
i_engraverRev.field = QLatin1String("REVERSEENGRAVER");
i_engraverRev.label_p = engraverRevLabel;
i_engraverRev.lineEdit_p = engraverRevLineEdit;
list_string_view_items.push_back(i_engraverRev);

SchemaViewItem i_issuer;
i_issuer.field = QLatin1String("ISSUER");
i_issuer.label_p = issuerLabel;
i_issuer.lineEdit_p = issuerLineEdit;
list_string_view_items.push_back(i_issuer);

SchemaViewItem i_authority;
i_authority.field = QLatin1String("AUTHORITY");
i_authority.label_p = authorityLabel;
i_authority.lineEdit_p = authorityLineEdit;
list_string_view_items.push_back(i_authority);

SchemaViewItem i_mint;
i_mint.field = QLatin1String("MINT");
i_mint.label_p = mintLabel;
i_mint.lineEdit_p = mintLineEdit;
list_string_view_items.push_back(i_mint);

SchemaViewItem i_mintageNote;
i_mintageNote.field = QLatin1String("MINTAGE_NOTE");
i_mintageNote.label_p = mintageNoteLabel;
i_mintageNote.lineEdit_p = mintageNoteLineEdit;
list_string_view_items.push_back(i_mintageNote);

SchemaViewItem i_obverseSymbol;
i_obverseSymbol.field = QLatin1String("OBVERSESYMBOL");
i_obverseSymbol.label_p = obverseSymbolLabel;
i_obverseSymbol.lineEdit_p = obverseSymbolLineEdit;
list_string_view_items.push_back(i_obverseSymbol);

SchemaViewItem i_obverseType;
i_obverseType.field = QLatin1String("OBVERSETYPE");
i_obverseType.label_p = obverseTypeLabel;
i_obverseType.lineEdit_p = obverseTypeLineEdit;
list_string_view_items.push_back(i_obverseType);

SchemaViewItem i_obverseLegend1;
i_obverseLegend1.field = QLatin1String("OBVERSELEGEND1");
i_obverseLegend1.label_p = obverseLegend1Label;
i_obverseLegend1.lineEdit_p = obverseLegend1LineEdit;
list_string_view_items.push_back(i_obverseLegend1);

SchemaViewItem i_obverseLegend2;
i_obverseLegend2.field = QLatin1String("OBVERSELEGEND2");
i_obverseLegend2.label_p = obverseLegend2Label;
i_obverseLegend2.lineEdit_p = obverseLegend2LineEdit;
list_string_view_items.push_back(i_obverseLegend2);

SchemaViewItem i_obvDieID;
i_obvDieID.field = QLatin1String("OBVERSEDIEID");
i_obvDieID.label_p = obvDieIDLabel;
i_obvDieID.lineEdit_p = obvDieIDLineEdit;
list_string_view_items.push_back(i_obvDieID);

SchemaViewItem i_obverseCountermark;
i_obverseCountermark.field = QLatin1String("OBVERSECOUNTERMARK");
i_obverseCountermark.label_p = obverseCountermarkLabel;
i_obverseCountermark.lineEdit_p = obverseCountermarkLineEdit;
list_string_view_items.push_back(i_obverseCountermark);

SchemaViewItem i_reverseSymbol;
i_reverseSymbol.field = QLatin1String("REVERSESYMBOL");
i_reverseSymbol.label_p = reverseSymbolLabel;
i_reverseSymbol.lineEdit_p = reverseSymbolLineEdit;
list_string_view_items.push_back(i_reverseSymbol);

SchemaViewItem i_reverseType;
i_reverseType.field = QLatin1String("REVERSETYPE");
i_reverseType.label_p = reverseTypeLabel;
i_reverseType.lineEdit_p = reverseTypeLineEdit;
list_string_view_items.push_back(i_reverseType);

SchemaViewItem i_reverseLegend1;
i_reverseLegend1.field = QLatin1String("REVERSELEGEND1");
i_reverseLegend1.label_p = reverseLegend1Label;
i_reverseLegend1.lineEdit_p = reverseLegend1LineEdit;
list_string_view_items.push_back(i_reverseLegend1);

SchemaViewItem i_reverseLegend2;
i_reverseLegend2.field = QLatin1String("REVERSELEGEND2");
i_reverseLegend2.label_p = reverseLegend2Label;
i_reverseLegend2.lineEdit_p = reverseLegend2LineEdit;
list_string_view_items.push_back(i_reverseLegend2);

SchemaViewItem i_revDieID;
i_revDieID.field = QLatin1String("REVERSEDIEID");
i_revDieID.label_p = revDieIDLabel;
i_revDieID.lineEdit_p = revDieIDLineEdit;
list_string_view_items.push_back(i_revDieID);

SchemaViewItem i_reverseCountermark;
i_reverseCountermark.field = QLatin1String("REVERSECOUNTERMARK");
i_reverseCountermark.label_p = reverseCountermarkLabel;
i_reverseCountermark.lineEdit_p = reverseCountermarkLineEdit;
list_string_view_items.push_back(i_reverseCountermark);

SchemaViewItem i_from;
i_from.field = QLatin1String("FROMDATE");
i_from.label_p = fromDateLabel;
i_from.lineEdit_p = fromDateLineEdit;
list_string_view_items.push_back(i_from);

SchemaViewItem i_to;
i_to.field = QLatin1String("TODATE");
i_to.label_p = toDateLabel;
i_to.lineEdit_p = toDateLineEdit;
list_string_view_items.push_back(i_to);

SchemaViewItem i_dateOnObject;
i_dateOnObject.field = QLatin1String("DATEONOBJECT");
i_dateOnObject.label_p = dateOnObjectLabel;
i_dateOnObject.lineEdit_p = dateOnObjectLineEdit;
list_string_view_items.push_back(i_dateOnObject);

SchemaViewItem i_eraOnObject;
i_eraOnObject.field = QLatin1String("ERAONOBJECT");
i_eraOnObject.label_p = eraOnObjectLabel;
i_eraOnObject.lineEdit_p = eraOnObjectLineEdit;
list_string_view_items.push_back(i_eraOnObject);

SchemaViewItem i_rulerOnObject;
i_rulerOnObject.field = QLatin1String("RULERONOBJECT");
i_rulerOnObject.label_p = rulerOnObjectLabel;
i_rulerOnObject.lineEdit_p = rulerOnObjectLineEdit;
list_string_view_items.push_back(i_rulerOnObject);

SchemaViewItem i_region;
i_region.field = QLatin1String("REGION");
i_region.label_p = regionLabel;
i_region.lineEdit_p = regionLineEdit;
list_string_view_items.push_back(i_region);

SchemaViewItem i_findspot;
i_findspot.field = QLatin1String("FINDSPOT");
i_findspot.label_p = findspotLabel;
i_findspot.lineEdit_p = findspotLineEdit;
list_string_view_items.push_back(i_findspot);

SchemaViewItem i_coordinates;
i_coordinates.field = QLatin1String("COORDINATES");
i_coordinates.label_p = coordinatesLabel;
i_coordinates.lineEdit_p = coordinatesLineEdit;
list_string_view_items.push_back(i_coordinates);

SchemaViewItem i_status;
i_status.field = QLatin1String("STATUS");
i_status.label_p = statusLabel;
i_status.lineEdit_p = statusLineEdit;
list_string_view_items.push_back(i_status);

SchemaViewItem i_aq;
i_aq.field = QLatin1String("AQ_DATE");
i_aq.label_p = aqLabel;
i_aq.lineEdit_p = aqLineEdit;
list_string_view_items.push_back(i_aq);

SchemaViewItem i_loc;
i_loc.field = QLatin1String("LOCATION");
i_loc.label_p = locLabel;
i_loc.lineEdit_p = locLineEdit;
list_string_view_items.push_back(i_loc);

SchemaViewItem i_seller;
i_seller.field = QLatin1String("SELLER");
i_seller.label_p = sellerLabel;
i_seller.lineEdit_p = sellerLineEdit;
list_string_view_items.push_back(i_seller);

SchemaViewItem i_cust;
i_cust.field = QLatin1String("CUSTOMER");
i_cust.label_p = custLabel;
i_cust.lineEdit_p = custLineEdit;
list_string_view_items.push_back(i_cust);

SchemaViewItem i_title;
i_title.field = QLatin1String("TITLE");
i_title.label_p = titleLabel;
i_title.lineEdit_p = titleLineEdit;
list_string_view_items.push_back(i_title);

SchemaViewItem i_uniqueID;
i_uniqueID.field = QLatin1String("UNIQUEID");
i_uniqueID.label_p = uniqueIDLabel;
i_uniqueID.lineEdit_p = uniqueIDLineEdit;
list_string_view_items.push_back(i_uniqueID);

SchemaViewItem i_coll;
i_coll.field = QLatin1String("COLLECTION");
i_coll.label_p = collLabel;
i_coll.lineEdit_p = collLineEdit;
list_string_view_items.push_back(i_coll);

SchemaViewItem i_collID;
i_collID.field = QLatin1String("COLLECTIONID");
i_collID.label_p = collIDLabel;
i_collID.lineEdit_p = collIDLineEdit;
list_string_view_items.push_back(i_collID);

SchemaViewItem i_projID;
i_projID.field = QLatin1String("PROJECTID");
i_projID.label_p = projIDLabel;
i_projID.lineEdit_p = projIDLineEdit;
list_string_view_items.push_back(i_projID);

SchemaViewItem i_hoard;
i_hoard.field = QLatin1String("HOARD");
i_hoard.label_p = hoardLabel;
i_hoard.lineEdit_p = hoardLineEdit;
list_string_view_items.push_back(i_hoard);

SchemaViewItem i_catalog;
i_catalog.field = QLatin1String("CATALOGID");
i_catalog.label_p = catalogLabel;
i_catalog.lineEdit_p = catalogLineEdit;
list_string_view_items.push_back(i_catalog);

SchemaViewItem i_history;
i_history.field = QLatin1String("HISTORY_NOTE");
i_history.label_p = historyLabel;
i_history.lineEdit_p = historyLineEdit;
list_string_view_items.push_back(i_history);

SchemaViewItem i_recordDate;
i_recordDate.field = QLatin1String("RECORDDATE");
i_recordDate.label_p = recordDateLabel;
i_recordDate.lineEdit_p = recordDateLineEdit;
list_string_view_items.push_back(i_recordDate);

SchemaViewItem i_recordType;
i_recordType.field = QLatin1String("RECORDTYPE");
i_recordType.label_p = recordTypeLabel;
i_recordType.lineEdit_p = recordTypeLineEdit;
list_string_view_items.push_back(i_recordType);

SchemaViewItem i_res1;
i_res1.field = QLatin1String("RESERVED_1");
i_res1.label_p = res1Label;
i_res1.lineEdit_p = res1LineEdit;
list_string_view_items.push_back(i_res1);

SchemaViewItem i_res2;
i_res2.field = QLatin1String("RESERVED_2");
i_res2.label_p = res2Label;
i_res2.lineEdit_p = res2LineEdit;
list_string_view_items.push_back(i_res2);

SchemaViewItem i_res3;
i_res3.field = QLatin1String("RESERVED_3");
i_res3.label_p = res3Label;
i_res3.lineEdit_p = res3LineEdit;
list_string_view_items.push_back(i_res3);

SchemaViewItem i_res4;
i_res4.field = QLatin1String("RESERVED_4");
i_res4.label_p = res4Label;
i_res4.lineEdit_p = res4LineEdit;
list_string_view_items.push_back(i_res4);

SchemaViewItem i_res5;
i_res5.field = QLatin1String("RESERVED_5");
i_res5.label_p = res5Label;
i_res5.lineEdit_p = res5LineEdit;
list_string_view_items.push_back(i_res5);

SchemaViewItem i_res6;
i_res6.field = QLatin1String("RESERVED_6");
i_res6.label_p = res6Label;
i_res6.lineEdit_p = res6LineEdit;
list_string_view_items.push_back(i_res6);

SchemaViewItem i_res7;
i_res7.field = QLatin1String("RESERVED_7");
i_res7.label_p = res7Label;
i_res7.lineEdit_p = res7LineEdit;
list_string_view_items.push_back(i_res7);

SchemaViewItem i_res8;
i_res8.field = QLatin1String("RESERVED_8");
i_res8.label_p = res8Label;
i_res8.lineEdit_p = res8LineEdit;
list_string_view_items.push_back(i_res8);

SchemaViewItem i_res9;
i_res9.field = QLatin1String("RESERVED_9");
i_res9.label_p = res9Label;
i_res9.lineEdit_p = res9LineEdit;
list_string_view_items.push_back(i_res9);

SchemaViewItem i_res10;
i_res10.field = QLatin1String("RESERVED_10");
i_res10.label_p = res10Label;
i_res10.lineEdit_p = res10LineEdit;
list_string_view_items.push_back(i_res10);

SchemaViewItem i_res11;
i_res11.field = QLatin1String("RESERVED_11");
i_res11.label_p = res11Label;
i_res11.lineEdit_p = res11LineEdit;
list_string_view_items.push_back(i_res11);

SchemaViewItem i_res12;
i_res12.field = QLatin1String("RESERVED_12");
i_res12.label_p = res12Label;
i_res12.lineEdit_p = res12LineEdit;
list_string_view_items.push_back(i_res12);

SchemaViewItem i_res20;
i_res20.field = QLatin1String("RESERVED_20");
i_res20.label_p = res20Label;
i_res20.lineEdit_p = res20LineEdit;
list_string_view_items.push_back(i_res20);

// ints
SchemaViewItem i_year;
i_year.field = QLatin1String("OBJ_YEAR");
i_year.label_p = yearLabel;
i_year.lineEdit_p = yearLineEdit;
list_int_view_items.push_back(i_year);

SchemaViewItem i_rar;
i_rar.field = QLatin1String("RATING");
i_rar.label_p = rarLabel;
i_rar.lineEdit_p = rarLineEdit;
list_int_view_items.push_back(i_rar);

SchemaViewItem i_res13;
i_res13.field = QLatin1String("RESERVED_13");
i_res13.label_p = res13Label;
i_res13.lineEdit_p = res13LineEdit;
list_int_view_items.push_back(i_res13);

SchemaViewItem i_res14;
i_res14.field = QLatin1String("RESERVED_14");
i_res14.label_p = res14Label;
i_res14.lineEdit_p = res14LineEdit;
list_int_view_items.push_back(i_res14);

SchemaViewItem i_res15;
i_res15.field = QLatin1String("RESERVED_15");
i_res15.label_p = res15Label;
i_res15.lineEdit_p = res15LineEdit;
list_int_view_items.push_back(i_res15);

SchemaViewItem i_res16;
i_res16.field = QLatin1String("RESERVED_16");
i_res16.label_p = res16Label;
i_res16.lineEdit_p = res16LineEdit;
list_int_view_items.push_back(i_res16);

QObject::connect( actionExit,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( close_app() ) );
QObject::connect( actionOpen_database,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( open_db() ) );
QObject::connect( actionRecord,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( add_record() ) );
QObject::connect( deleteToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( delete_record() ) );
QObject::connect( tableView,
                  SIGNAL( pressed(QModelIndex) ),
                  this,
                  SLOT( index_selected(QModelIndex) ) );
QObject::connect( catTableView,
                  SIGNAL( pressed(QModelIndex) ),
                  this,
                  SLOT( cat_index_selected() ) );
QObject::connect( auctTableView,
                  SIGNAL( pressed(QModelIndex) ),
                  this,
                  SLOT( auct_index_selected() ) );
QObject::connect( geoTableView,
                  SIGNAL( pressed(QModelIndex) ),
                  this,
                  SLOT( geo_index_selected() ) );
QObject::connect( otherTableView,
                  SIGNAL( pressed(QModelIndex) ),
                  this,
                  SLOT( other_index_selected() ) );
QObject::connect( actionEditRM,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( edit_record() ) );
QObject::connect( editToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( edit_record() ) );
QObject::connect( actionCopyRM,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( copy_record() ) );
QObject::connect( copyToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( copy_record() ) );
QObject::connect( actionDeleteRM,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_record() ) );
QObject::connect( actionBackup_DB,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( run_backup() ) );
QObject::connect( actionRestore_DB,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( run_restore() ) );
QObject::connect( actionDisconnect,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( disconnect_db() ) );
QObject::connect( actionAlbums,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( albums() ) );
QObject::connect( actionCatN,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( add_cat_row() ) );
QObject::connect( addCatRowToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( add_cat_row() ) );
QObject::connect( actionCatE,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( edit_cat_row() ) );
QObject::connect( actionCatD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( del_cat_row() ) );
QObject::connect( delCatRowToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( del_cat_row() ) );
QObject::connect( actionAuctN,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( add_auct_row() ) );
QObject::connect( addAuctRowToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( add_auct_row() ) );
QObject::connect( actionAuctE,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( edit_auct_row() ) );
QObject::connect( actionAuctD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( del_auct_row() ) );
QObject::connect( delAuctRowToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( del_auct_row() ) );
QObject::connect( actionGeoN,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( add_geo_row() ) );
QObject::connect( addGeoRowToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( add_geo_row() ) );
QObject::connect( actionGeoE,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( edit_geo_row() ) );
QObject::connect( actionGeoD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( del_geo_row() ) );
QObject::connect( delGeoRowToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( del_geo_row() ) );
QObject::connect( actionOtherN,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( add_other_row() ) );
QObject::connect( addOtherRowToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( add_other_row() ) );
QObject::connect( actionOtherE,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( edit_other_row() ) );
QObject::connect( actionOtherD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( del_other_row() ) );
QObject::connect( delOtherRowToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( del_other_row() ) );
QObject::connect( actionContacts,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_contacts() ) );
QObject::connect( actionLook,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( select_style() ) );
QObject::connect( setFilterButton,
                  SIGNAL( toggled(bool) ),
                  this,
                  SLOT( set_filter(bool) ) );
QObject::connect( actionImN,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( add_image() ) );
QObject::connect( addImageToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( add_image() ) );
QObject::connect( actionDocN,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( add_document() ) );
QObject::connect( addDocToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( add_document() ) );
QObject::connect( actionImD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( del_im_row() ) );
QObject::connect( delImageToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( del_im_row() ) );
QObject::connect( actionDocD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( del_doc_row() ) );
QObject::connect( delDocToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( del_doc_row() ) );
QObject::connect( imagesTableView,
                  SIGNAL( clicked(QModelIndex) ),
                  this,
                  SLOT( im_index_selected(QModelIndex) ) );
QObject::connect( tabWidget,
                  SIGNAL( currentChanged(int) ),
                  this,
                  SLOT( tab_ind_changed(int) ) );
QObject::connect( actionObvI,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( set_obverse_icon() ) );
QObject::connect( actionRevI,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( set_reverse_icon() ) );
QObject::connect( actionEdgeI,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( set_edge_icon() ) );
QObject::connect( itemTabWidget,
                  SIGNAL( currentChanged(int) ),
                  this,
                  SLOT( tab_ind_changed_rel(int) ) );
QObject::connect( referencesTabWidget,
                  SIGNAL( currentChanged(int) ),
                  this,
                  SLOT( tab_ind_changed_refer(int) ) );
QObject::connect( binaryTabWidget,
                  SIGNAL( currentChanged(int) ),
                  this,
                  SLOT( tab_ind_changed_binary(int) ) );
QObject::connect( actionFont,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( set_font() ) );
QObject::connect( actionDefaultFont,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( set_default_font() ) );
QObject::connect( actionAttr,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( album_attr() ) );
QObject::connect( actionImage,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_image_rmb() ) );
QObject::connect( viewerToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( show_image_button() ) );
QObject::connect( actionSaveAs,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( save_image_as() ) );
QObject::connect( actionCharts,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_charts() ) );
QObject::connect( backButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( set_back() ) );
QObject::connect( nextButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( set_next() ) );
QObject::connect( actionSaveDoc,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( save_doc_as() ) );
QObject::connect( actionFullObv,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_full_obv() ) );
QObject::connect( actionFullRev,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_full_rev() ) );
QObject::connect( actionFullEdge,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_full_edge() ) );
QObject::connect( saveEditButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( save_desc() ) );
QObject::connect( actionRussian,
                  SIGNAL( triggered(bool) ),
                  this,
                  SLOT( switch_to_ru(bool) ) );
QObject::connect( actionRussian,
                  SIGNAL( triggered(bool) ),
                  this,
                  SLOT( remember_ru(bool) ) );
QObject::connect( actionEnglish,
                  SIGNAL( triggered(bool) ),
                  this,
                  SLOT( switch_to_en(bool) ) );
QObject::connect( actionEnglish,
                  SIGNAL( triggered(bool) ),
                  this,
                  SLOT( remember_en(bool) ) );
QObject::connect( actionGerman,
                  SIGNAL( triggered(bool) ),
                  this,
                  SLOT( switch_to_de(bool) ) );
QObject::connect( actionGerman,
                  SIGNAL( triggered(bool) ),
                  this,
                  SLOT( remember_de(bool) ) );
/*
QObject::connect( actionZh,
                  SIGNAL( triggered(bool) ),
                  this,
                  SLOT( switch_to_zh_CN(bool) ) );
QObject::connect( actionZh,
                  SIGNAL( triggered(bool) ),
                  this,
                  SLOT( remember_zh_CN(bool) ) );
*/
QObject::connect( actionImportMSXML,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( import_dialog() ) );
QObject::connect( actionClipboard,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( image_to_clipboard() ) );
QObject::connect( actionEmpty,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_all_rows() ) );
QObject::connect( actionAbout,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_creds() ) );
QObject::connect( actionManual,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_manual() ) );
QObject::connect( actionConfView,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( conf_view() ) );
QObject::connect( charsToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( show_chars() ) );
QObject::connect( newToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( add_record() ) );
QObject::connect( actionExportMSXML,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( export_xml() ) );
QObject::connect( actionUpdateRM,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( fast_update() ) );
QObject::connect( fieldToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( fast_update() ) );
QObject::connect( actionPrintRM,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( print_item() ) );
QObject::connect( docToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( print_item() ) );
QObject::connect( codecsToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( show_codecs() ) );
QObject::connect( descTextEdit,
                  SIGNAL( textChanged() ),
                  this,
                  SLOT( update_edit_button() ) );
QObject::connect( previewHtmlToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( preview_html() ) );
QObject::connect( printToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( print_file() ) );
QObject::connect( actionValue,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( show_value() ) );
QObject::connect( actionPricelist,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( print_pricelist() ) );
QObject::connect( actionReport,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( print_report() ) );
QObject::connect( pdfToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( print_pdf() ) );
QObject::connect( collSelectToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( albums() ) );
QObject::connect( actionSQLQuery,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( run_query() ) );                  
QObject::connect( actionBrowseDB,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( browse_db() ) );                  
QObject::connect( actionExpSQLITE,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( export_sqlite() ) );                  
                  
}

MainWindow::~MainWindow()
{
}

void MainWindow::closeEvent(QCloseEvent * e)
{

    if (blocking == 1)
    {
    e->ignore();
    QMessageBox::information( this,
                              tr("Can not close."),
                              tr("Task is running."), 0 );
    return;
    }

delete_models();
    {
    TabModel1 * old_model = qobject_cast<TabModel1 *>( tableView->model() );
        if (NULL != old_model)
        {
        old_model->clear();
        }
    tableView->setModel( new TabModel1 );
    delete old_model;
    }

    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if (true == db.isOpen())
        {
        close_db();
        }
    }

    {
    QSqlDatabase ext_db = QSqlDatabase::database("extern", false);
        if (true == ext_db.isOpen())
        {
        close_db();
        }
    }
QSqlDatabase::removeDatabase("collection");
QSqlDatabase::removeDatabase("external");
writeSettings();
delete m0;
delete m1;
qApp->quit();
exit(0);
}

void MainWindow::close_app()
{
qApp->closeAllWindows();
exit(0);
}

void MainWindow::open_db()
{
DbDialog dialog;
    if (dialog.exec() != QDialog::Accepted)
    {
    return;
    }
    else
    {
    disconnect_db();
        {
        QMap<QString, QVariant> m;
        m = dialog.return_config();
        QString driver = QLatin1String("QIBASE");
            if (m.value("is_emb_db").toString() == QLatin1String("y") )
            {
            buildin_db = true;
            }
            else
            {
            buildin_db = false;
            }

        QSqlDatabase db = QSqlDatabase::addDatabase(driver, "collection");

            if(m.value("is_emb_db").toString() == QLatin1String("y") )
            {
            QString db_nat = db_root;
            db_nat.append( QDir::separator() );
            db_name = QLatin1String("COLL0.FDB");
            db_nat.append(db_name);
            db.setDatabaseName(db_nat);
            db.setUserName( QLatin1String("SYSDBA") );
            db.setPassword( QLatin1String("masterp") );
            }
            else
            {
            db.setHostName( m.value("host").toString() );
            db.setPort( m.value("port").toInt() );
            QString db_nat = QDir::toNativeSeparators( m.value("db").toString() );
            db_name = db_nat.section( QDir::separator(), -1 );
            db.setDatabaseName(db_nat);
            db.setUserName( m.value("user").toString() );
            db.setPassword( m.value("pass").toString() );
            }

        bool opened = db.open();
            if (true == opened)
            {
            QString s =
            QLatin1String("select album_name,album_num from albums_reg where album_id = 1");
            QString album_num = QLatin1String("");
            QString album_name = QLatin1String("");
            QSqlQuery query(s, db);
                while (query.next())
                {
                album_name = query.value(0).toString();
                album_num = query.value(1).toString();
                }
            query.clear();
            db_opened = true;

            QString s0 = QLatin1String("select count(1) from albums_reg");
            QSqlQuery query0(s0, db);
                while ( query0.next() )
                {
                number_of_collections = query0.value(0).toLongLong();
                }
            query0.clear();

            set_album( QLatin1String("a001"),
                       album_num,
                       album_name );
            }
            else
            {
            QMessageBox::critical( this,
                                   tr("Can not open database."),
                                   db.lastError().text() );
            close_db();
            return;
            }
        }
    }
statusBar()->showMessage( tr("DB opened"), 2000 );
}

void MainWindow::index_selected (QModelIndex index)
{
TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());
    if (NULL == model)
    {
    return;
    }

actionCopyRM->setDisabled(false);
    if ( true == tableView->currentIndex().isValid() )
    {
    actionDeleteRM->setDisabled(false);
    }
    else
    {
    actionDeleteRM->setDisabled(true);
    }

QItemSelectionModel * selectionModel = tableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

unsigned int y = 0;
    for (int i = 0; i < currentSelection.size(); ++i)
    {
        if (y == 2)
        {
        break;
        }
    y += 1;
    }

    if (y < 2)
    {
    actionEditRM->setDisabled(false);
    actionPrintRM->setDisabled(false);
    }
    else
    {
    actionEditRM->setDisabled(true);
    actionPrintRM->setDisabled(true);
    }

view_index = QModelIndex(index);
view_record = model->record(view_index.row());
    if ( view_index.row() == 0 )
    {
    nextButton->setEnabled(true);
    backButton->setEnabled(false);
    }
    else
    {
    nextButton->setEnabled(true);
    backButton->setEnabled(true);
    }

set_view(index);
}

void MainWindow::commit_main( QSqlRecord record,
                              QModelIndex index,
                              bool new_item,
                              bool fast_update )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());

    if ( model == NULL )
    {
    set_empty_view();
    return;
    }

    if ( record.isNull("ID") )
    {
    QMessageBox::critical( this,
                           "Error",
                           "ID is NULL." );
    return;
    }

QSplashScreen * splash = new QSplashScreen( create_splash_image(),
                                            Qt::WindowStaysOnTopHint );
splash->show();
qApp->processEvents();

bool success = false;
    if ( true == new_item )
    {
    success = model->insertRecord( -1, record );
    }
    else
    {
    success = model->setRecord( index.row(), record );
    }

    if ( true != success )
    {
    splash->close();
    delete splash;

    QMessageBox::critical( this,
                           tr("Update failed"),
                           tr("The database reported : %1").arg(model->lastError().text() ) );
    model->select();
    return;
    }

bool model_submit = model->submitAll();

    if ( true != model_submit )
    {
    splash->close();
    delete splash;
    QMessageBox::critical( this,
                           tr("Submit failed"),
                           tr("The database reported : %1").arg(model->lastError().text() ) );
    model->revertAll();
    return;
    }

    if ( true == new_item )
    {
    tableView->sortByColumn(0, Qt::DescendingOrder);
        if (model->lastError().type() != QSqlError::NoError)
        {
        statusBar()->showMessage( model->lastError().text(), 10000 );
        qApp->processEvents();
        }

    QModelIndex zero_index = QModelIndex( model->index( 0, 0 ) );
        if ( true == zero_index.isValid() )
        {
        tableView->selectRow(0);
        set_view(zero_index);
        }
        else
        {
        splash->close();
        delete splash;
        QMessageBox::information( this,
                                  tr("Success"),
                                  tr("Update successed.\nNote: View is empty.\nProbabaly filter hides the new item.") );
        set_empty_view();
        return;
        }
    }
    else
    {
        if ( true == fast_update )
        {
        model->select();
            if ( model->lastError().type() != QSqlError::NoError )
            {
            statusBar()->showMessage( model->lastError().text(), 10000 );
            }

        tableView->clearSelection();
        set_empty_view();
        }
        else
        {
        model->select();
            if ( model->lastError().type() != QSqlError::NoError )
            {
            statusBar()->showMessage( model->lastError().text(), 10000 );
            }

        int idx = 0;
            while ( idx < index.row() )
            {
            model->fetchMore();
            idx += 256;
            }

        bool ok = check_index();

            if ( true == ( model->record( index.row() ).value("ID").toLongLong() ==
                           record.value("ID").toLongLong() )
                      &&
                 true == ok )
            {
            tableView->selectRow( index.row() );
            set_view(index);
            }
            else
            {
            set_empty_view();
            splash->close();
            delete splash;
            QMessageBox::information( this,
                                      tr("Success"),
                                      tr("Update successed.\nNote: Model\'s sorting changed.") );
            return;
            }
        }
    }
splash->close();
delete splash;
}

void MainWindow::edit_record()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error"),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = tableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord( model->record(currentSelection.at(0).row() ) );

EditWidget * editWidget = new EditWidget(collection_attrs);
editWidget->set_record( record, currentSelection.at(0), opened_album );
editWidget->show();

QObject::connect( editWidget,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, bool, bool ) ),
                  this,
                  SLOT( commit_main( QSqlRecord, QModelIndex, bool, bool ) ) );
}

void MainWindow::add_record()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error" ),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

TabModel1 * model = qobject_cast<TabModel1 *>( tableView->model() );
    if (NULL == model)
    {
    set_empty_view();
    return;
    }
EditWidget * editWidget = new EditWidget(collection_attrs);
editWidget->new_record(opened_album);
editWidget->show();

QObject::connect( editWidget,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, bool, bool ) ),
                  this,
                  SLOT( commit_main( QSqlRecord, QModelIndex, bool, bool ) ) );
}

void MainWindow::run_backup()
{
    if ( true == db_opened )
    {
    QMessageBox mBox;
    mBox.setWindowTitle( tr("Confirm") );
    mBox.setIcon( QMessageBox::Question );
    mBox.setText( tr("Close the database and go to backup dialog?") );
    mBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        switch (mBox.exec())
        {
            case QMessageBox::No:
            return;
            break;

            default:
            break;
        }
    disconnect_db();
    }

BackupWidget * backupWidget = new BackupWidget();
backupWidget->show();
}

void MainWindow::run_restore()
{
QString restore_message = tr("Recommended way to restore the database : ");
restore_message.append( QLatin1String("\n") );
restore_message.append( tr("restart the application, then CANCEL connection") );
restore_message.append( QLatin1String("\n") );
restore_message.append( tr("dialog and go directly to restore dialog.") );
restore_message.append( QLatin1String("\n") );
restore_message.append( tr("    Go ahead to restore dialog now?") );

QMessageBox mBox;
mBox.setWindowTitle( tr("Information") );
mBox.setIcon( QMessageBox::Information );
mBox.setText( restore_message );
mBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    switch ( mBox.exec() )
    {
        case QMessageBox::No:
        return;
        break;

        default:
        break;
    }

disconnect_db();
RestoreWidget * restoreWidget = new RestoreWidget();
restoreWidget->show();
}

void MainWindow::set_view( QModelIndex index )
{
delete_binary_models();
delete_references_models();
iconObvLabel->clear();
iconRevLabel->clear();
iconEdgeLabel->clear();
icons_data_set = false;
previewLabel->clear();
desc_data_set = false;
descTextEdit->blockSignals(true);
descTextEdit->clear();
descTextEdit->blockSignals(false);
textChangedLabel->clear();
saveTextLabel->clear();

QString record_str = QLatin1String("");
QString state_str = QLatin1String("");

view_index = QModelIndex(index);
TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());
QSqlRecord record = QSqlRecord( model->record( view_index.row() ) );
view_record = QSqlRecord(record);

qint64 id = Q_INT64_C(-1);
    if (!record.isNull("ID") )
    {
    id = record.value("ID").toLongLong();
    itemTabWidget->setDisabled(false);
    }
    else
    {
    view_index = QModelIndex();
    view_record = QSqlRecord();
    QMessageBox::critical( this,
                           "Error",
                           "ID is NULL." );
    set_empty_view();
    return;
    }

    if ( !record.isNull("DENOMINATION") )
    {
    record_str.append( record.value("DENOMINATION").toString() );
    }

    if ( !record.isNull("OBJ_YEAR") )
    {
    record_str.append( QLatin1String(" ") );
    record_str.append( QString::number( record.value("OBJ_YEAR").toInt() ) );
    }

    if ( !record.isNull("STATE") )
    {
    state_str.append( record.value("STATE").toString() );
        if ( true != state_str.isEmpty() )
        {
        record_str.append( QLatin1String(" ") );
        record_str.append(state_str);
        }
    }

    for (int xx = 0; xx < list_string_view_items.size(); ++xx)
    {
        if (!record.isNull( list_string_view_items.at(xx).field ) )
        {
        QString s_value = record.value( list_string_view_items.at(xx).field ).toString();
            if ( NULL != list_string_view_items.at(xx).label_p )
            {
            list_string_view_items.at(xx).label_p->setDisabled(false);
            }
            if ( NULL != list_string_view_items.at(xx).lineEdit_p )
            {
            list_string_view_items.at(xx).lineEdit_p->setDisabled(false);
            list_string_view_items.at(xx).lineEdit_p->setText(s_value);
            list_string_view_items.at(xx).lineEdit_p->setCursorPosition(0);
            }
        }
        else
        {
            if ( NULL != list_string_view_items.at(xx).lineEdit_p )
            {
            list_string_view_items.at(xx).lineEdit_p->clear();
            list_string_view_items.at(xx).lineEdit_p->setDisabled(true);
            }
            if ( NULL != list_string_view_items.at(xx).label_p )
            {
            list_string_view_items.at(xx).label_p->setDisabled(true);
            }
        }
    }

    for (int xx = 0; xx < list_int_view_items.size(); ++xx)
    {
        if (!record.isNull( list_int_view_items.at(xx).field ) )
        {
        int i_value = record.value( list_int_view_items.at(xx).field ).toInt();
            if ( NULL != list_int_view_items.at(xx).label_p )
            {
            list_int_view_items.at(xx).label_p->setDisabled(false);
            }
            if ( NULL != list_int_view_items.at(xx).lineEdit_p )
            {
            list_int_view_items.at(xx).lineEdit_p->setDisabled(false);
            list_int_view_items.at(xx).lineEdit_p->setText( QString::number(i_value) );
            list_int_view_items.at(xx).lineEdit_p->setCursorPosition(0);
            }
        }
        else
        {
            if ( NULL != list_int_view_items.at(xx).lineEdit_p )
            {
            list_int_view_items.at(xx).lineEdit_p->clear();
            list_int_view_items.at(xx).lineEdit_p->setDisabled(true);
            }
            if ( NULL != list_int_view_items.at(xx).label_p )
            {
            list_int_view_items.at(xx).label_p->setDisabled(true);
            }
        }
    }

    if (!record.isNull("MINTAGE") )
    {
    bool to_int_ok = false;
    int i_value = record.value("MINTAGE").toInt(&to_int_ok);
        if ( true == to_int_ok )
        {
        QString formatted_mintage = QString("%L1").arg(i_value);
        mintageLabel->setDisabled(false);
        mintageLineEdit->setDisabled(false);
        mintageLineEdit->setText(formatted_mintage);
        mintageLineEdit->setCursorPosition(0);
        }
        else
        {
        mintageLabel->setDisabled(true);
        mintageLineEdit->setDisabled(true);
        mintageLineEdit->clear();
        }
    }
    else
    {
    mintageLabel->setDisabled(true);
    mintageLineEdit->setDisabled(true);
    mintageLineEdit->clear();
    }

    if (!record.isNull("GRADED") )
    {
    QString graded = record.value("GRADED").toString();
        if ( graded == QLatin1String("Y") )
        {
        gradedCheckBox->setChecked(true);
        }
    }
    else
    {
    gradedCheckBox->setChecked(false);
    }

    if (!record.isNull("CERTIFIED") )
    {
    QString certified = record.value("CERTIFIED").toString();
        if ( certified == QLatin1String("Y") )
        {
        certCheckBox->setChecked(true);
        }
    }
    else
    {
    certCheckBox->setChecked(false);
    }

    if (!record.isNull("WEIGHT") )
    {
    double weight = record.value("WEIGHT").toDouble();
    QString weight_unit;
    QString weight_s;
        if (!record.isNull("WEIGHT_UNIT") )
        {
        weight_unit = record.value("WEIGHT_UNIT").toString();
        }
    QString weight_label = weight_s.setNum(weight);
    weight_label.append( QLatin1String(" ") );
    weight_label.append(weight_unit);
    weightLabel->setDisabled(false);
    weightLineEdit->setDisabled(false);
    weightLineEdit->setText(weight_label);
    weightLineEdit->setCursorPosition(0);
    }
    else
    {
    weightLineEdit->clear();
    weightLineEdit->setDisabled(true);
    weightLabel->setDisabled(true);
    }

    if (!record.isNull("DIAM") )
    {
    double diam = record.value("DIAM").toDouble();
    QString diam_unit;
    QString diam_s;
        if (!record.isNull("DIAM_UNIT") )
        {
        diam_unit = record.value("DIAM_UNIT").toString();
        }
    QString diam_label = diam_s.setNum(diam) + " " + diam_unit;
    diamLabel->setDisabled(false);
    diamLineEdit->setDisabled(false);
    diamLineEdit->setText(diam_label);
    diamLineEdit->setCursorPosition(0);
    }
    else
    {
    diamLineEdit->clear();
    diamLineEdit->setDisabled(true);
    diamLabel->setDisabled(true);
    }

    if (!record.isNull("THICKNESS") )
    {
    double thick = record.value("THICKNESS").toDouble();
    QString thick_unit;
    QString thick_s;
        if (!record.isNull("THICKNESS_UNIT") )
        {
        thick_unit = record.value("THICKNESS_UNIT").toString();
        }
    QString thick_label = thick_s.setNum(thick) + " " + thick_unit;
    thickLabel->setDisabled(false);
    thickLineEdit->setDisabled(false);
    thickLineEdit->setText(thick_label);
    thickLineEdit->setCursorPosition(0);
    }
    else
    {
    thickLineEdit->clear();
    thickLineEdit->setDisabled(true);
    thickLabel->setDisabled(true);
    }

    if (!record.isNull("LATITUDE") )
    {
    double latitude = record.value("LATITUDE").toDouble();
    QString latitude_str = QString::number(latitude);
    latitudeLabel->setDisabled(false);
    latitudeLineEdit->setDisabled(false);
    latitudeLineEdit->setText(latitude_str);
    latitudeLineEdit->setCursorPosition(0);
    }
    else
    {
    latitudeLineEdit->clear();
    latitudeLineEdit->setDisabled(true);
    latitudeLabel->setDisabled(true);
    }

    if (!record.isNull("LONGITUDE") )
    {
    double longitude = record.value("LONGITUDE").toDouble();
    QString longitude_str = QString::number(longitude);
    longitudeLabel->setDisabled(false);
    longitudeLineEdit->setDisabled(false);
    longitudeLineEdit->setText(longitude_str);
    longitudeLineEdit->setCursorPosition(0);
    }
    else
    {
    longitudeLineEdit->clear();
    longitudeLineEdit->setDisabled(true);
    longitudeLabel->setDisabled(true);
    }

    if (!record.isNull("AQ_PRICE") )
    {
    double price = record.value("AQ_PRICE").toDouble();
    QString price_curr;
    QString price_s;
        if (!record.isNull("AQ_CURR") )
        {
        price_curr = record.value("AQ_CURR").toString();
        }
    QString price_label = price_s.setNum(price) + " " + price_curr;
    priceLabel->setDisabled(false);
    priceLineEdit->setDisabled(false);
    priceLineEdit->setText(price_label);
    priceLineEdit->setCursorPosition(0);
    }
    else
    {
    priceLineEdit->clear();
    priceLineEdit->setDisabled(true);
    priceLabel->setDisabled(true);
    }

    if (!record.isNull("ACT_VALUE") )
    {
    double estim = record.value("ACT_VALUE").toDouble();
    QString estim_curr;
    QString estim_s;
        if (!record.isNull("ACT_CURR") )
        {
        estim_curr = record.value("ACT_CURR").toString();
        }
    QString estim_label = estim_s.setNum(estim) + " " + estim_curr;
    estimLabel->setDisabled(false);
    estimLineEdit->setDisabled(false);
    estimLineEdit->setText(estim_label);
    estimLineEdit->setCursorPosition(0);
    }
    else
    {
    estimLineEdit->clear();
    estimLineEdit->setDisabled(true);
    estimLabel->setDisabled(true);
    }

    if (!record.isNull("SOLD_DATE"))
    {
    int date_int = record.value("SOLD_DATE").toInt();
    QString date_str = QString::number(date_int);
    QDate date  = QDate::fromString(date_str, "yyyyMMdd");

        if ( true == date.isValid() )
        {
        soldDateLabel->setDisabled(false);
        soldDateLineEdit->setDisabled(false);
        soldDateLineEdit->setText( date.toString("d MMMM yyyy") );
        soldDateLineEdit->setCursorPosition(0);
        }
        else
        {
        soldDateLabel->setDisabled(true);
        soldDateLineEdit->setDisabled(true);
        soldDateLineEdit->clear();
        }
    }
    else
    {
    soldDateLabel->setDisabled(true);
    soldDateLineEdit->setDisabled(true);
    soldDateLineEdit->clear();
    }

    if (!record.isNull("RESERVED_17") )
    {
    double res17 = record.value("RESERVED_17").toDouble();
    res17Label->setDisabled(false);
    res17LineEdit->setDisabled(false);
    res17LineEdit->setText( QString::number(res17) );
    res17LineEdit->setCursorPosition(0);
    }
    else
    {
    res17LineEdit->clear();
    res17LineEdit->setDisabled(true);
    res17Label->setDisabled(true);
    }

    if (!record.isNull("RESERVED_18") )
    {
    double res18 = record.value("RESERVED_18").toDouble();
    res18Label->setDisabled(false);
    res18LineEdit->setDisabled(false);
    res18LineEdit->setText( QString::number(res18) );
    res18LineEdit->setCursorPosition(0);
    }
    else
    {
    res18LineEdit->clear();
    res18LineEdit->setDisabled(true);
    res18Label->setDisabled(true);
    }

    if (!record.isNull("RESERVED_19") )
    {
    qint64 res19 = record.value("RESERVED_19").toLongLong();
    res19Label->setDisabled(false);
    res19LineEdit->setDisabled(false);
    res19LineEdit->setText( QString::number(res19) );
    res19LineEdit->setCursorPosition(0);
    }
    else
    {
    res19LineEdit->clear();
    res19LineEdit->setDisabled(true);
    res19Label->setDisabled(true);
    }

tabWidget->setTabEnabled(1, true);
recordLineEdit->setText(record_str);
}

void MainWindow::set_empty_view()
{
delete_models();

recordLineEdit->clear();
nominalLineEdit->clear();
nominalLabel->setDisabled(true);
stateLineEdit->clear();
stateLabel->setDisabled(true);
epochLineEdit->clear();
epochLabel->setDisabled(true);
yearLineEdit->clear();
yearLabel->setDisabled(true);
marksLineEdit->clear();
marksLabel->setDisabled(true);
edgeLineEdit->clear();
edgeLabel->setDisabled(true);
materialLineEdit->clear();
materialLabel->setDisabled(true);
rarLineEdit->clear();
rarLabel->setDisabled(true);
gradedCheckBox->setChecked(false);
certCheckBox->setChecked(false);
condLineEdit->clear();
condLabel->setDisabled(true);
certLineEdit->clear();
condLineEdit->setDisabled(true);
condLineEdit->clear();
weightLineEdit->clear();
diamLineEdit->clear();
diamLabel->setDisabled(true);
axis1LineEdit->clear();
axis1Label->setDisabled(true);
axis2LineEdit->clear();
axis2Label->setDisabled(true);
shapeLineEdit->clear();
shapeLabel->setDisabled(true);
thickLineEdit->clear();
thickLabel->setDisabled(true);
edgeIDLineEdit->clear();
edgeIDLabel->setDisabled(true);
typeLineEdit->clear();
typeLabel->setDisabled(true);
undertypeLineEdit->clear();
undertypeLabel->setDisabled(true);
edgeLegendLineEdit->clear();
edgeLegendLineEdit->setDisabled(true);
artistObvLineEdit->clear();
artistObvLabel->setDisabled(true);
artistRevLineEdit->clear();
artistRevLabel->setDisabled(true);
engraverObvLineEdit->clear();
engraverObvLabel->setDisabled(true);
engraverRevLineEdit->clear();
engraverRevLabel->setDisabled(true);
issuerLineEdit->clear();
issuerLabel->setDisabled(true);
authorityLineEdit->clear();
authorityLabel->setDisabled(true);
mintageNoteLineEdit->clear();
mintageNoteLabel->setDisabled(true);
mintLineEdit->clear();
mintLabel->setDisabled(true);
mintageLineEdit->clear();
mintageLabel->setDisabled(true);
obverseSymbolLineEdit->clear();
obverseSymbolLabel->setDisabled(true);
obverseTypeLineEdit->clear();
obverseTypeLabel->setDisabled(true);
obverseLegend1LineEdit->clear();
obverseLegend1Label->setDisabled(true);
obverseLegend2LineEdit->clear();
obverseLegend2Label->setDisabled(true);
obvDieIDLineEdit->clear();
obvDieIDLabel->setDisabled(true);
obverseCountermarkLineEdit->clear();
obverseCountermarkLabel->setDisabled(true);
reverseSymbolLineEdit->clear();
reverseSymbolLabel->setDisabled(true);
reverseTypeLineEdit->clear();
reverseTypeLabel->setDisabled(true);
reverseLegend1LineEdit->clear();
reverseLegend1Label->setDisabled(true);
reverseLegend2LineEdit->clear();
reverseLegend2Label->setDisabled(true);
revDieIDLineEdit->clear();
revDieIDLabel->setDisabled(true);
reverseCountermarkLineEdit->clear();
reverseCountermarkLabel->setDisabled(true);
fromDateLineEdit->clear();
fromDateLabel->setDisabled(true);
toDateLineEdit->clear();
toDateLabel->setDisabled(true);
dateOnObjectLineEdit->clear();
dateOnObjectLabel->setDisabled(true);
eraOnObjectLineEdit->clear();
eraOnObjectLabel->setDisabled(true);
rulerOnObjectLineEdit->clear();
rulerOnObjectLabel->setDisabled(true);
regionLineEdit->clear();
regionLabel->setDisabled(true);
findspotLineEdit->clear();
findspotLabel->setDisabled(true);
coordinatesLineEdit->clear();
coordinatesLabel->setDisabled(true);
latitudeLineEdit->clear();
latitudeLabel->setDisabled(true);
longitudeLineEdit->clear();
longitudeLabel->setDisabled(true);
statusLineEdit->clear();
statusLabel->setDisabled(true);
aqLineEdit->clear();
aqLabel->setDisabled(true);
locLineEdit->clear();
locLabel->setDisabled(true);
sellerLineEdit->clear();
sellerLabel->setDisabled(true);
priceLineEdit->clear();
priceLabel->setDisabled(true);
estimLineEdit->clear();
estimLabel->setDisabled(true);
soldDateLabel->setDisabled(true);
soldDateLineEdit->clear();
custLineEdit->clear();
custLabel->setDisabled(true);
titleLineEdit->clear();
titleLabel->setDisabled(true);
uniqueIDLineEdit->clear();
uniqueIDLabel->setDisabled(true);
collLineEdit->clear();
collLabel->setDisabled(true);
collIDLineEdit->clear();
collIDLabel->setDisabled(true);
projIDLineEdit->clear();
projIDLabel->setDisabled(true);
hoardLineEdit->clear();
hoardLabel->setDisabled(true);
catalogLineEdit->clear();
catalogLabel->setDisabled(true);
historyLineEdit->clear();
historyLabel->setDisabled(true);
recordDateLineEdit->clear();
recordDateLabel->setDisabled(true);
recordTypeLineEdit->clear();
recordTypeLabel->setDisabled(true);
res1LineEdit->clear();
res1Label->setDisabled(true);
res2LineEdit->clear();
res2Label->setDisabled(true);
res3LineEdit->clear();
res3Label->setDisabled(true);
res4LineEdit->clear();
res4Label->setDisabled(true);
res5LineEdit->clear();
res5Label->setDisabled(true);
res6LineEdit->clear();
res6Label->setDisabled(true);
res7LineEdit->clear();
res7Label->setDisabled(true);
res8LineEdit->clear();
res8Label->setDisabled(true);
res9LineEdit->clear();
res9Label->setDisabled(true);
res10LineEdit->clear();
res10Label->setDisabled(true);
res11LineEdit->clear();
res11Label->setDisabled(true);
res12LineEdit->clear();
res12Label->setDisabled(true);
res13LineEdit->clear();
res13Label->setDisabled(true);
res14LineEdit->clear();
res14Label->setDisabled(true);
res15LineEdit->clear();
res15Label->setDisabled(true);
res16LineEdit->clear();
res16Label->setDisabled(true);
res17LineEdit->clear();
res17Label->setDisabled(true);
res18LineEdit->clear();
res18Label->setDisabled(true);
res19LineEdit->clear();
res19Label->setDisabled(true);
res20LineEdit->clear();
res20Label->setDisabled(true);

iconObvLabel->clear();
iconRevLabel->clear();
iconEdgeLabel->clear();
previewLabel->clear();

descTextEdit->blockSignals(true);
descTextEdit->clear();
descTextEdit->blockSignals(false);
textChangedLabel->clear();
saveTextLabel->clear();

view_index = QModelIndex();
view_record = QSqlRecord();
tableView->clearSelection();
tabWidget->setTabEnabled(1, false);
}

void MainWindow::disconnect_db()
{
close_album();
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if (true == db.isOpen())
        {
        close_db();
        }
    }

db_opened = false;
QSqlDatabase::removeDatabase("collection");
}

void MainWindow::albums()
{
AlbumDialog * albumDialog = new AlbumDialog;
albumDialog->show();
    if ( albumDialog->exec() != QDialog::Accepted )
    {
    albumDialog->close();
    delete albumDialog;
    return;
    }
    else
    {
    QMap<QString, QString> m;
    m = albumDialog->return_selected();
        if ( true == m.value("table").isEmpty() ||
             true == m.value("table").isNull() )
        {
        albumDialog->close();
        delete albumDialog;
        return;
        }
        else
        {
        set_album( m.value("table"),
                   m.value("num"),
                   m.value("name") );
        }
    albumDialog->close();
    delete albumDialog;
    }
}

void MainWindow::set_album( QString table,
                            QString num,
                            QString name )
{
    if ( true == table.isEmpty() )
    {
    QMessageBox::critical( this,
                           "Error",
                           "Table name is empty." );
    opened_album = QLatin1String("");
    opened_album_num = QLatin1String("");
    opened_album_name = QLatin1String("");
    return;
    }

    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        close_db();
        return;
        }
    }

QSplashScreen * splash = new QSplashScreen( create_splash_image() );
splash->show();
qApp->processEvents();

Schema * schema = new Schema();
    if ( NULL == schema )
    {
    return;
    }
QMap<int, QString> columns_headers = schema->headers();
int columns_count = schema->columns_count();

TabModel1 * model = new TabModel1( 0, QSqlDatabase::database("collection") );
model->setTable(table);
model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    if (model->lastError().type() != QSqlError::NoError)
    {
    splash->close();
    QMessageBox::critical( this,
                           tr("Error"),
                           model->lastError().text() );
    opened_album = QLatin1String("");
    opened_album_num = QLatin1String("");
    opened_album_name = QLatin1String("");
    set_empty_view();
    model->clear();
    delete model;
    delete splash;
    model = NULL;
    return;
    }
    else
    {
    opened_album = table;
    opened_album_num = num;
    opened_album_name = name;

    set_album_view(opened_album);

    QString rn = QLatin1String("<b>");
    rn.append(num);
    rn.append(QLatin1String("</b>"));
    albumNumLabel->setText(rn);
    albumNameLabel->setText(name);

    model->setHeaderData(  0, Qt::Horizontal, tr("ID") );
        for ( int i = 0; i < columns_count; i++)
        {
            if ( columns_show.value(i) == 1 )
            {
            model->setHeaderData( i, Qt::Horizontal, columns_headers.value(i) );
            }
        }

    TabModel1 * old_model = qobject_cast<TabModel1 *>(tableView->model());

    tableView->setModel(model);
    tableView->sortByColumn(0, Qt::DescendingOrder);
        if (model->lastError().type() != QSqlError::NoError)
        {
        QMessageBox::warning( this,
                              tr("Error"),
                              model->lastError().text() );
        }

        for ( int i = 0; i < columns_count; i++)
        {
            if ( columns_show.value(i) == 1 )
            {
            tableView->setColumnWidth( i, column_width.value(i) );
            }
            else
            {
            tableView->hideColumn(i);
            }
        }

        if (NULL != old_model)
        {
        old_model->clear();
        }
    delete old_model;
    old_model = NULL;

    tableView->setItemDelegateForColumn( 4, new RarDelegate() );

        if ( true == setFilterButton->isChecked() )
        {
        setFilterButton->blockSignals(true);
        setFilterButton->setChecked(false);
        qApp->processEvents();
        setFilterButton->blockSignals(false);
        }
    set_empty_view();
    load_attrs();
    read_indicies( table.toUpper() ); 
    }

delete schema;
QString s = tr("Collection");
s.append( QLatin1String(" ") );
s.append(opened_album_num);
s.append( QLatin1String(" ") );
s.append(opened_album_name);
s.append( QLatin1String(" ") );
s.append( tr("loaded") );
s.append( QLatin1String(".") );
statusBar()->showMessage(s, 3000);

update_actions(false);

splash->close();
qApp->processEvents();
delete splash;
}

void MainWindow::update_actions(bool state)
{
newToolButton->setDisabled(state);
deleteToolButton->setDisabled(state);
editToolButton->setDisabled(state);
collSelectToolButton->setDisabled(state);
actionAlbums->setDisabled(state);
actionAttr->setDisabled(state);
actionCharts->setDisabled(state);
actionConfView->setDisabled(state);
actionEmpty->setDisabled(state);
actionValue->setDisabled(state);
actionDisconnect->setDisabled(state);
setFilterButton->setDisabled(state);
actionRecord->setDisabled(state);
actionEditRM->setDisabled(state);
actionCopyRM->setDisabled(state);
actionDeleteRM->setDisabled(state);
actionImportMSXML->setDisabled(state);
actionExportMSXML->setDisabled(state);
//actionPricelist->setDisabled(state);
//actionReport->setDisabled(state);
//actionExpSQLITE->setDisabled(state);
//actionImpSQLITE->setDisabled(state);
actionSQLQuery->setDisabled(state);
actionPrintRM->setDisabled(state);
actionUpdateRM->setDisabled(state);
}

void MainWindow::copy_record()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

TabModel1 * model = qobject_cast<TabModel1 *>( tableView->model() );
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = tableView->selectionModel();
    if (NULL == selectionModel)
    {
    return;
    }

QModelIndexList currentSelection = selectionModel->selectedRows(0);
    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Information"),
                              tr("Nothing is selected.") );
    return;
    }

QMap<QString, QString> m;
CopyDialog * copyDialog = new CopyDialog();
copyDialog->show();
    if ( copyDialog->exec() != QDialog::Accepted )
    {
    copyDialog->close();
    delete copyDialog;
    return;
    }
    else
    {
    m = copyDialog->return_selected();
    copyDialog->close();
    delete copyDialog;
    }

QList<qint64> ids_list;
QString table = QLatin1String("");
QString table_num = QLatin1String("");
QString table_name = QLatin1String("");
QString source_table = opened_album;

QSplashScreen * splash = new QSplashScreen( create_splash_image() );
splash->show();
splash->showMessage("Processing Selection ...");
qApp->processEvents();

    for (int i = 0; i < currentSelection.size(); ++i)
    {
    ids_list << model->record( currentSelection.at(i).row() ).value("ID").toLongLong();
    }

    if ( m.value("use_current") == QLatin1String("TRUE") )
    {
    table = source_table;
    }
    else
    {
    table =  m.value("table");
    table_num =  m.value("num");
    table_name =  m.value("name");
        if ( true == table.isEmpty() )
        {
        QMessageBox::warning( this,
                              tr("Warning"),
                              tr("No collection selected.") );
        return;
        }
    }

bool filter_used = false;
    if ( true == setFilterButton->isChecked() )
    {
    filter_used = true;
    }
close_album();

splash->close();
delete splash;

ProgressDialog * pw = new ProgressDialog( ids_list.size() );
pw->show();

Schema * schema = new Schema();
    if ( NULL == schema )
    {
    return;
    }
QString columns_str = schema->columns_for_query();
int columns_count = schema->columns_count();

blocking = 1;

    for ( int y = 0; y < ids_list.size(); y++ )
    {
    qint64 id_to_copy = ids_list.at(y);
    QString message = tr("Processing ID");
    message.append( QLatin1String(" ") );
    message.append( QString::number(id_to_copy) );
    qApp->processEvents();
    statusBar()->showMessage(message, 2000);
    pw->set_value(y);
    qApp->processEvents();

    qint64 new_id = Q_INT64_C(-1);
    QString s0 = QLatin1String("select gen_id(");
    s0.append(table);
    s0.append(QLatin1String("_a_gen, 1) from rdb$database"));
    QSqlQuery query0(s0, db);
        while ( query0.next() )
        {
        new_id = query0.value(0).toLongLong();
        }
    query0.clear();

    QString s_select = QLatin1String("select ");
    s_select.append(columns_str);
    s_select.append( QLatin1String(" from ") );
    s_select.append(source_table);
    s_select.append( QLatin1String(" where id = ") );
    s_select.append( QString::number(id_to_copy) );
    QSqlQuery query_select(s_select, db);
    QMap<int, QVariant> item_data;
        while ( query_select.next() )
        {
            for ( int x = 1; x < columns_count; ++x )
            {
            item_data[x] = query_select.value(x);
            }
        }
    query_select.clear();

    QString s_insert = QLatin1String("insert into ");
    s_insert.append(table);
    s_insert.append( QLatin1String("(") );
    s_insert.append(columns_str);
    s_insert.append( QLatin1String(")") );
    s_insert.append( QLatin1String(" values ") );
    s_insert.append( QLatin1String("(") );
    s_insert.append( QString::number(new_id) );
    s_insert.append( QLatin1String(",") );
        for ( int i = 1; i < columns_count; ++i )
        {
            if ( i == ( columns_count - 1 ) )
            {
            s_insert.append( process_value( i, item_data.value(i), false ) );
            }
            else
            {
            s_insert.append( process_value( i, item_data.value(i), true ) );
            }
        }
    s_insert.append( QLatin1String(")") );
    QSqlQuery query_insert(s_insert, db);
        if ( true == query_insert.lastError().isValid() )
        {
        QMessageBox::warning( this,
                              QLatin1String("Query Error Message (main)"),
                              query_insert.lastError().text() );
        query_insert.clear();
        continue;
        }
    query_insert.clear();

        // Images
        if ( m.value("copy_images") == QLatin1String("TRUE") )
        {
        QStringList images_list;
        QString s1 = QLatin1String("select image_id from ");
        s1.append(source_table);
        s1.append( QLatin1String("_images where coin_id = ") );
        s1.append( QString::number(id_to_copy) );
        QSqlQuery query1(s1, db);
            while ( query1.next() )
            {
            images_list << QString::number(query1.value(0).toLongLong() );
            }
        query1.clear();
            if ( true != images_list.isEmpty() )
            {
                for ( int x = 0; x < images_list.size(); ++x )
                {
                qint64 new_image_id = Q_INT64_C(-1);
                QString s8 = QLatin1String("select gen_id(");
                s8.append(table);
                s8.append( QLatin1String("_images_gen, 1) from rdb$database") );
                QSqlQuery query8(s8, db);
                    while ( query8.next() )
                    {
                    new_image_id = query8.value(0).toLongLong();
                    }
                query8.clear();
                QString s9 = QLatin1String("insert into ");
                s9.append(table);
                s9.append( QLatin1String("_images (image_id,coin_id,file_name") );
                s9.append( QLatin1String(",saved_as,is_obv_icon,is_rev_icon,is_edge_icon) \n") );
                s9.append( QLatin1String("select ") );
                s9.append( QString::number(new_image_id) );
                s9.append( QLatin1String(",") );
                s9.append( QString::number(new_id) );
                s9.append( QLatin1String(",file_name,saved_as") );
                s9.append( QLatin1String(",is_obv_icon,is_rev_icon,is_edge_icon from ") );
                s9.append(source_table);
                s9.append( QLatin1String("_images where image_id = ") );
                s9.append( images_list.at(x) );
                QSqlQuery query9(s9, db);
                    if ( true == query9.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          QLatin1String("Query Error Message (image)"),
                                          query9.lastError().text() );
                    }
                query9.clear();
                QString s10 = QLatin1String("insert into ");
                s10.append(table);
                s10.append( QLatin1String("_im_blobs (image_id,coin_id,image_b) \n") );
                s10.append( QLatin1String("select ") );
                s10.append( QString::number(new_image_id) );
                s10.append( QLatin1String(",") );
                s10.append( QString::number(new_id) );
                s10.append( QLatin1String(",image_b from ") );
                s10.append(source_table);
                s10.append( QLatin1String("_im_blobs where image_id = ") );
                s10.append( images_list.at(x) );
                QSqlQuery query10(s10, db);
                    if ( true == query10.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          QLatin1String("Query Error Message (image BLOB)"),
                                          query10.lastError().text() );
                    }
                query10.clear();
                }
            }
        }

        // Documents
        if ( m.value("copy_docs") == QLatin1String("TRUE") )
        {
        QStringList docs_list;
        QString s2 = QLatin1String("select doc_id from ");
        s2.append(source_table);
        s2.append( QLatin1String("_documents where coin_id = ") );
        s2.append( QString::number(id_to_copy) );
        QSqlQuery query2(s2, db);
            while ( query2.next() )
            {
            docs_list << QString::number(query2.value(0).toLongLong() );
            }
        query2.clear();
            if ( true != docs_list.isEmpty() )
            {
                for ( int x = 0; x < docs_list.size(); ++x )
                {
                qint64 new_doc_id = Q_INT64_C(-1);
                QString s11 = QLatin1String("select gen_id(");
                s11.append(table);
                s11.append(QLatin1String("_documents_gen, 1) from rdb$database"));
                QSqlQuery query11(s11, db);
                    while ( query11.next() )
                    {
                    new_doc_id = query11.value(0).toLongLong();
                    }
                query11.clear();
                QString s12 = QLatin1String("insert into ");
                s12.append(table);
                s12.append( QLatin1String("_documents (doc_id,coin_id,file_name") );
                s12.append( QLatin1String(",saved_as) \n") );
                s12.append( QLatin1String("select ") );
                s12.append( QString::number(new_doc_id) );
                s12.append( QLatin1String(",") );
                s12.append( QString::number(new_id) );
                s12.append( QLatin1String(",file_name,saved_as from ") );
                s12.append(source_table);
                s12.append( QLatin1String("_documents where doc_id = ") );
                s12.append( docs_list.at(x) );
                QSqlQuery query12(s12, db);
                    if ( true == query12.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          QLatin1String("Query Error Message (document)"),
                                          query12.lastError().text() );
                    }
                query12.clear();
                QString s13 = QLatin1String("insert into ");
                s13.append(table);
                s13.append( QLatin1String("_doc_blobs (doc_id,coin_id,doc_b) \n") );
                s13.append( QLatin1String("select ") );
                s13.append( QString::number(new_doc_id) );
                s13.append( QLatin1String(",") );
                s13.append( QString::number(new_id) );
                s13.append( QLatin1String(",doc_b from ") );
                s13.append(source_table);
                s13.append( QLatin1String("_doc_blobs where doc_id = ") );
                s13.append( docs_list.at(x) );
                QSqlQuery query13(s13, db);
                    if ( true == query13.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          QLatin1String("Query Error Message (document BLOB)"),
                                          query13.lastError().text() );
                    }
                query13.clear();
                }
            }
        }

        // Description
        if ( m.value("copy_desc") == QLatin1String("TRUE") )
        {
        QString s7 = QLatin1String("insert into ");
        s7.append(table);
        s7.append( QLatin1String("_desc_blobs (coin_id,desc_b) \n") );
        s7.append( QLatin1String("select ") );
        s7.append( QString::number(new_id) );
        s7.append( QLatin1String(",desc_b from ") );
        s7.append(source_table);
        s7.append( QLatin1String("_desc_blobs where coin_id = ") );
        s7.append( QString::number(id_to_copy) );
        QSqlQuery query7(s7, db);
            if ( true == query7.lastError().isValid() )
            {
            QMessageBox::warning( this,
                                  QLatin1String("Query Error Message (description)"),
                                  query7.lastError().text() );
            }
        query7.clear();
        }

        if ( m.value("copy_refs") == QLatin1String("TRUE") )
        {
        // Catalogs
        QStringList cats_list;
        QString s3 = QLatin1String("select cat_id from ");
        s3.append(source_table);
        s3.append( QLatin1String("_catalogs where coin_id = ") );
        s3.append( QString::number(id_to_copy) );
        QSqlQuery query3(s3, db);
            while ( query3.next() )
            {
            cats_list << QString::number( query3.value(0).toLongLong() );
            }
        query3.clear();
            if ( true != cats_list.isEmpty() )
            {
                for ( int x = 0; x < cats_list.size(); ++x )
                {
                qint64 new_cat_id = Q_INT64_C(-1);
                QString s11 = QLatin1String("select gen_id(");
                s11.append(table);
                s11.append(QLatin1String("_catalogs_gen, 1) from rdb$database"));
                QSqlQuery query11(s11, db);
                    while ( query11.next() )
                    {
                    new_cat_id = query11.value(0).toLongLong();
                    }
                query11.clear();
                QString s14 = QLatin1String("insert into ");
                s14.append(table);
                s14.append( QLatin1String("_catalogs (cat_id,coin_id") );
                s14.append( QLatin1String(",cat_name,int_id,cat_note") );
                s14.append( QLatin1String(",cat_pr_f,cat_pr_vf,cat_pr_xf,cat_pr_unc,cat_curr") );
                s14.append( QLatin1String(") \n") );
                s14.append( QLatin1String("select ") );
                s14.append( QString::number(new_cat_id) );
                s14.append( QLatin1String(",") );
                s14.append( QString::number(new_id) );
                s14.append( QLatin1String(",cat_name,int_id,cat_note") );
                s14.append( QLatin1String(",cat_pr_f,cat_pr_vf,cat_pr_xf,cat_pr_unc,cat_curr") );
                s14.append( QLatin1String(" from ") );
                s14.append(source_table);
                s14.append( QLatin1String("_catalogs where cat_id = ") );
                s14.append( cats_list.at(x) );
                QSqlQuery query14(s14, db);
                    if ( true == query14.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          QLatin1String("Query Error Message (catalogs)"),
                                          query14.lastError().text() );
                    }
                query14.clear();
                }
            }

        // Auctions
        QStringList aucts_list;
        QString s4 = QLatin1String("select auct_id from ");
        s4.append(source_table);
        s4.append( QLatin1String("_auctions where coin_id = ") );
        s4.append( QString::number(id_to_copy) );
        QSqlQuery query4(s4, db);
            while ( query4.next() )
            {
            aucts_list << QString::number( query4.value(0).toLongLong() );
            }
        query4.clear();
            if ( true != aucts_list.isEmpty() )
            {
                for ( int x = 0; x < aucts_list.size(); ++x )
                {
                qint64 new_auct_id = Q_INT64_C(-1);
                QString s16 = QLatin1String("select gen_id(");
                s16.append(table);
                s16.append(QLatin1String("_auctions_gen, 1) from rdb$database"));
                QSqlQuery query16(s16, db);
                    while ( query16.next() )
                    {
                    new_auct_id = query16.value(0).toLongLong();
                    }
                query16.clear();
                QString s15 = QLatin1String("insert into ");
                s15.append(table);
                s15.append( QLatin1String("_auctions (auct_id,coin_id") );
                s15.append( QLatin1String(",auct_name,auct_date,auct_note,auct_cond,auct_pr,auct_curr") );
                s15.append( QLatin1String(") \n") );
                s15.append( QLatin1String("select ") );
                s15.append( QString::number(new_auct_id) );
                s15.append( QLatin1String(",") );
                s15.append( QString::number(new_id) );
                s15.append( QLatin1String(",auct_name,auct_date,auct_note,auct_cond,auct_pr,auct_curr") );
                s15.append( QLatin1String(" from ") );
                s15.append(source_table);
                s15.append( QLatin1String("_auctions where auct_id = ") );
                s15.append( aucts_list.at(x) );
                QSqlQuery query15(s15, db);
                    if ( true == query15.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          QLatin1String("Query Error Message (auctions)"),
                                          query15.lastError().text() );
                    }
                query15.clear();
                }
            }

        // Spots
        QStringList spots_list;
        QString s5 = QLatin1String("select spot_id from ");
        s5.append(source_table);
        s5.append( QLatin1String("_spots where coin_id = ") );
        s5.append( QString::number(id_to_copy) );
        QSqlQuery query5(s5, db);
            while ( query5.next() )
            {
            spots_list << QString::number( query5.value(0).toLongLong() );
            }
        query5.clear();
            if ( true != spots_list.isEmpty() )
            {
                for ( int x = 0; x < spots_list.size(); ++x )
                {
                qint64 new_spot_id = Q_INT64_C(-1);
                QString s17 = QLatin1String("select gen_id(");
                s17.append(table);
                s17.append(QLatin1String("_spots_gen, 1) from rdb$database"));
                QSqlQuery query17(s17, db);
                    while ( query17.next() )
                    {
                    new_spot_id = query17.value(0).toLongLong();
                    }
                query17.clear();
                QString s18 = QLatin1String("insert into ");
                s18.append(table);
                s18.append( QLatin1String("_spots (spot_id,coin_id") );
                s18.append( QLatin1String(",spot_name,note,coord,latitude,longitude,spot_date") );
                s18.append( QLatin1String(") \n") );
                s18.append( QLatin1String("select ") );
                s18.append( QString::number(new_spot_id) );
                s18.append( QLatin1String(",") );
                s18.append( QString::number(new_id) );
                s18.append( QLatin1String(",spot_name,note,coord,latitude,longitude,spot_date") );
                s18.append( QLatin1String(" from ") );
                s18.append(source_table);
                s18.append( QLatin1String("_spots where spot_id = ") );
                s18.append( spots_list.at(x) );
                QSqlQuery query18(s18, db);
                    if ( true == query18.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          QLatin1String("Query Error Message (spots)"),
                                          query18.lastError().text() );
                    }
                query18.clear();
                }
            }

        // Other
        QStringList others_list;
        QString s6 = QLatin1String("select other_id from ");
        s6.append(source_table);
        s6.append( QLatin1String("_other where coin_id = ") );
        s6.append( QString::number(id_to_copy) );
        QSqlQuery query6(s6, db);
            while ( query6.next() )
            {
            others_list << QString::number( query6.value(0).toLongLong() );
            }
        query6.clear();
            if ( true != others_list.isEmpty() )
            {
                for ( int x = 0; x < others_list.size(); ++x )
                {
                qint64 new_other_id = Q_INT64_C(-1);
                QString s20 = QLatin1String("select gen_id(");
                s20.append(table);
                s20.append(QLatin1String("_other_gen, 1) from rdb$database"));
                QSqlQuery query20(s20, db);
                    while ( query20.next() )
                    {
                    new_other_id = query20.value(0).toLongLong();
                    }
                query20.clear();
                QString s19 = QLatin1String("insert into ");
                s19.append(table);
                s19.append( QLatin1String("_other (other_id,coin_id") );
                s19.append( QLatin1String(",name,text_1,text_2,other_date") );
                s19.append( QLatin1String(") \n") );
                s19.append( QLatin1String("select ") );
                s19.append( QString::number(new_other_id) );
                s19.append( QLatin1String(",") );
                s19.append( QString::number(new_id) );
                s19.append( QLatin1String(",name,text_1,text_2,other_date") );
                s19.append( QLatin1String(" from ") );
                s19.append(source_table);
                s19.append( QLatin1String("_other where other_id = ") );
                s19.append( others_list.at(x) );
                QSqlQuery query19(s19, db);
                    if ( true == query19.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          QLatin1String("Query Error Message (other)"),
                                          query19.lastError().text() );
                    }
                query19.clear();
                }
            }
        }
    }

delete schema;

blocking = 0;

qApp->processEvents();

set_album( table,
           table_num,
           table_name );
    if ( m.value("use_current") == QLatin1String("TRUE") )
    {
        if ( true == filter_used ||
             true != filter_.isEmpty() )
        {
        TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());
            if (NULL == model)
            {
            set_empty_view();
            return;
            }

        setFilterButton->blockSignals(true);
        setFilterButton->setChecked(true);
        model->setFilter(filter_);
        //model->select();
            if ( model->lastError().type() != QSqlError::NoError )
            {
            statusBar()->showMessage( model->lastError().text(), 10000 );
            }
        qApp->processEvents();
        setFilterButton->blockSignals(false);
        }
    }

pw->close();
delete pw;
}

void MainWindow::delete_record()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = tableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Information"),
                              tr("Nothing is selected.") );
    return;
    }

QMessageBox mBox;
mBox.setWindowTitle( tr("Confirm") );
mBox.setIcon( QMessageBox::Question );
mBox.setText( tr("        Delete?") );
mBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No );
    switch ( mBox.exec() )
    {
        case QMessageBox::No:
        return;
        break;

        default:
        break;
    }

QStringList coin_ids;
QStringList images_file_names;
QStringList documents_file_names;

    for ( int i = 0; i < currentSelection.size(); ++i )
    {
    coin_ids << QString::number( model->record( currentSelection.at(i).row() ).value("ID").toLongLong() );
    }

ProgressDialog * pw = new ProgressDialog( coin_ids.size() );
pw->show();
qApp->processEvents();

QString table = opened_album;

blocking = 1;

int count = 0;
    for ( int x = 0; x < coin_ids.size(); x += 512 )
    {
    QStringList tl;
        for ( int y = x; y <= x + 511; y += 1 )
        {
            if ( y >= coin_ids.size() )
            {
            break;
            }
        count += 1;
        QString mes_s = tr("Deleting ID");
        mes_s.append( QLatin1String(" ") );
        mes_s.append( coin_ids.at(y) );
        tl << coin_ids.at(y);
        statusBar()->showMessage(mes_s, 2000);
        pw->set_value(count);
        qApp->processEvents();
        }

    QString delete_s = QLatin1String("delete from ");
    delete_s.append(table);
    delete_s.append( QLatin1String(" where id in (") );
    delete_s.append( tl.join(",") );
    delete_s.append( QLatin1String(")") );
    QSqlQuery delete_query(delete_s, db);
        if ( true == delete_query.lastError().isValid() )
        {
        QMessageBox::warning( this,
                              QLatin1String("Query Error Message (delete)"),
                              delete_query.lastError().text() );
        }
    delete_query.clear();
    }

blocking = 0;
qApp->processEvents();
pw->close();
delete pw;

model->select();
    if ( model->lastError().type() != QSqlError::NoError )
    {
    QMessageBox::warning( this,
                          tr("Warning"),
                          model->lastError().text() );
    }

set_empty_view();
}

void MainWindow::set_data( QString table,
                           QModelIndex index,
                           QLatin1String data_type )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

bool ok = check_index();
    if (true != ok)
    {
    return;
    }

TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());
qint64 id = Q_INT64_C(-1);
id = model->record(index.row()).value("ID").toLongLong();
QString filter = QLatin1String("coin_id=");
filter.append( QString::number(id) );

    if ( data_type == QLatin1String("images") )
    {
    // Images view
    QSqlTableModel * old_images_model = qobject_cast<QSqlTableModel *>(imagesTableView->model());
    QSqlTableModel * images_model = new QSqlTableModel(0, db);
    images_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    images_model->setTable( table + QLatin1String("_images") );
    images_model->setFilter(filter);
    images_model->select();
        if ( images_model->lastError().type() != QSqlError::NoError )
        {
        statusBar()->showMessage( images_model->lastError().text(), 10000 );
        }
    images_model->setHeaderData(2, Qt::Horizontal, tr("File name") );
    images_model->setHeaderData(3, Qt::Horizontal, tr("Saved as") );
    imagesTableView->setModel(images_model);
    imagesTableView->setColumnWidth(2, 300 );
        if (NULL != old_images_model)
        {
        old_images_model->clear();
        }
    imagesTableView->hideColumn(0);
    imagesTableView->hideColumn(1);
    imagesTableView->hideColumn(4);
    imagesTableView->hideColumn(5);
    imagesTableView->hideColumn(6);
    imagesTableView->hideColumn(7);

    delete old_images_model;
    old_images_model = NULL;

    images_data_set = true;
    }
    else if ( data_type == QLatin1String("documents") )
    {
    // Documents view
    QSqlTableModel * old_docs_model = qobject_cast<QSqlTableModel *>(docsTableView->model());
    QSqlTableModel * docs_model = new QSqlTableModel(0, db);
    docs_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    docs_model->setTable( table + QLatin1String("_documents") );
    docs_model->setFilter(filter);
    docs_model->select();
        if ( docs_model->lastError().type() != QSqlError::NoError )
        {
        statusBar()->showMessage( docs_model->lastError().text(), 10000 );
        }
    docs_model->setHeaderData(2, Qt::Horizontal, tr("File name") );
    docs_model->setHeaderData(3, Qt::Horizontal, tr("Saved as") );
    docsTableView->setModel(docs_model);
    docsTableView->setColumnWidth(2, 220 );
        if (NULL != old_docs_model)
        {
        old_docs_model->clear();
        }
    docsTableView->hideColumn(0);
    docsTableView->hideColumn(1);
    docsTableView->hideColumn(4);
    delete old_docs_model;
    old_docs_model = NULL;

    documents_data_set = true;
    }
    else if ( data_type == QLatin1String("catalogs") )
    {
    // Catalog view
    QSqlTableModel * old_cat_model = qobject_cast<QSqlTableModel *>(catTableView->model());
    QSqlTableModel * cat_model = new QSqlTableModel(0, db);
    cat_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    cat_model->setTable( table + QLatin1String("_catalogs") );
    cat_model->setFilter(filter);
    cat_model->select();
        if ( cat_model->lastError().type() != QSqlError::NoError )
        {
        statusBar()->showMessage( cat_model->lastError().text(), 10000 );
        }
    cat_model->setHeaderData(2, Qt::Horizontal, tr("Catalog") );
    cat_model->setHeaderData(3, Qt::Horizontal, tr("ID") );
    cat_model->setHeaderData(4, Qt::Horizontal, tr("Note") );
    cat_model->setHeaderData(5, Qt::Horizontal, tr("Price F") );
    cat_model->setHeaderData(6, Qt::Horizontal, tr("Price VF") );
    cat_model->setHeaderData(7, Qt::Horizontal, tr("Price XF") );
    cat_model->setHeaderData(8, Qt::Horizontal, tr("Price UNC") );
    cat_model->setHeaderData(9, Qt::Horizontal, tr("Currency") );
    catTableView->setModel(cat_model);
    catTableView->setColumnWidth(4, 300 );
        if (NULL != old_cat_model)
        {
        old_cat_model->clear();
        }
    delete old_cat_model;
    old_cat_model = NULL;
    catTableView->hideColumn(0);
    catTableView->hideColumn(1);
    catTableView->hideColumn(10);

    catalogs_data_set = true;
    }
    else if ( data_type == QLatin1String("auctions") )
    {
    // Auction view
    QSqlTableModel * old_auct_model = qobject_cast<QSqlTableModel *>(auctTableView->model());
    QSqlTableModel * auct_model = new QSqlTableModel(0, db);
    auct_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    auct_model->setTable( table + QLatin1String("_auctions") );
    auct_model->setFilter(filter);
    auct_model->select();
        if ( auct_model->lastError().type() != QSqlError::NoError )
        {
        statusBar()->showMessage( auct_model->lastError().text(), 10000 );
        }
    auct_model->setHeaderData(2, Qt::Horizontal, tr("Auction") );
    auct_model->setHeaderData(3, Qt::Horizontal, tr("Date") );
    auct_model->setHeaderData(4, Qt::Horizontal, tr("Note") );
    auct_model->setHeaderData(5, Qt::Horizontal, tr("Condition") );
    auct_model->setHeaderData(6, Qt::Horizontal, tr("Price") );
    auct_model->setHeaderData(7, Qt::Horizontal, tr("Currency") );
    auctTableView->setModel(auct_model);
    auctTableView->setColumnWidth(4, 200 );
        if (NULL != old_auct_model)
        {
        old_auct_model->clear();
        }
    delete old_auct_model;
    old_auct_model = NULL;
    auctTableView->hideColumn(0);
    auctTableView->hideColumn(1);
    auctTableView->hideColumn(8);

    auctions_data_set = true;
    }
    else if ( data_type == QLatin1String("geo") )
    {
    // Geo view
    QSqlTableModel * old_geo_model = qobject_cast<QSqlTableModel *>(geoTableView->model());
    QSqlTableModel * geo_model = new QSqlTableModel(0, db);
    geo_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    geo_model->setTable( table + QLatin1String("_spots") );
    geo_model->setFilter(filter);
    geo_model->select();
        if (geo_model->lastError().type() != QSqlError::NoError)
        {
        statusBar()->showMessage( geo_model->lastError().text(), 10000 );
        }
    geo_model->setHeaderData(2, Qt::Horizontal, tr("Name") );
    geo_model->setHeaderData(3, Qt::Horizontal, tr("Note") );
    geo_model->setHeaderData(4, Qt::Horizontal, tr("Coord. System") );
    geo_model->setHeaderData(5, Qt::Horizontal, tr("Latitude") );
    geo_model->setHeaderData(6, Qt::Horizontal, tr("Longitude") );
    geo_model->setHeaderData(7, Qt::Horizontal, tr("Date") );
    geoTableView->setModel(geo_model);
    geoTableView->setColumnWidth(3, 200 );
        if (NULL != old_geo_model)
        {
        old_geo_model->clear();
        }
    delete old_geo_model;

    geoTableView->hideColumn(0);
    geoTableView->hideColumn(1);

    geo_data_set = true;
    }
    else if ( data_type == QLatin1String("other") )
    {
    // Other view
    QSqlTableModel * old_other_model = qobject_cast<QSqlTableModel *>(otherTableView->model());
    QSqlTableModel * other_model = new QSqlTableModel(0, db);
    other_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    other_model->setTable( table + QLatin1String("_other") );
    other_model->setFilter(filter);
    other_model->select();
        if (other_model->lastError().type() != QSqlError::NoError)
        {
        statusBar()->showMessage( other_model->lastError().text(), 10000 );
        }
    other_model->setHeaderData(2, Qt::Horizontal, tr("Name") );
    other_model->setHeaderData(3, Qt::Horizontal, tr("Note I") );
    other_model->setHeaderData(4, Qt::Horizontal, tr("Note II") );
    other_model->setHeaderData(5, Qt::Horizontal, tr("Date") );
    otherTableView->setModel(other_model);
    otherTableView->setColumnWidth(3, 140 );
    otherTableView->setColumnWidth(4, 140 );
        if (NULL != old_other_model)
        {
        old_other_model->clear();
        }
    delete old_other_model;

    otherTableView->hideColumn(0);
    otherTableView->hideColumn(1);

    other_data_set = true;
    }
    else
    {
    other_data_set = false;
    geo_data_set = false;
    auctions_data_set = false;
    catalogs_data_set = false;
    images_data_set = false;
    documents_data_set = false;
    return;
    }

itemTabWidget->setDisabled(false);
return;
}

void MainWindow::delete_models()
{
delete_binary_models();
delete_references_models();
previewLabel->clear();
iconObvLabel->clear();
iconRevLabel->clear();
iconEdgeLabel->clear();
descTextEdit->clear();
textChangedLabel->clear();
saveTextLabel->clear();

icons_data_set = false;
desc_data_set = false;
itemTabWidget->setDisabled(true);
}

void MainWindow::delete_binary_models()
{
// Images view
QSqlTableModel * old_images_model = qobject_cast<QSqlTableModel *>(imagesTableView->model());
    if (NULL != old_images_model)
    {
    old_images_model->clear();
    }
imagesTableView->setModel(new QSqlTableModel);
delete old_images_model;
old_images_model = NULL;

images_data_set = false;

// Docs view
QSqlTableModel * old_docs_model = qobject_cast<QSqlTableModel *>(docsTableView->model());
    if (NULL != old_docs_model)
    {
    old_docs_model->clear();
    }
docsTableView->setModel(new QSqlTableModel);
delete old_docs_model;
old_docs_model = NULL;

documents_data_set = false;
}

void MainWindow::delete_references_models()
{
// Catalog view
QSqlTableModel * old_cat_model = qobject_cast<QSqlTableModel *>(catTableView->model());
    if (NULL != old_cat_model)
    {
    old_cat_model->clear();
    }
catTableView->setModel(new QSqlTableModel);
delete old_cat_model;
old_cat_model = NULL;

catalogs_data_set = false;

// Auction view
QSqlTableModel * old_auct_model = qobject_cast<QSqlTableModel *>(auctTableView->model());
    if (NULL != old_auct_model)
    {
    old_auct_model->clear();
    }
auctTableView->setModel(new QSqlTableModel);
delete old_auct_model;
old_auct_model = NULL;

auctions_data_set = false;

// Geo view
QSqlTableModel * old_geo_model = qobject_cast<QSqlTableModel *>(geoTableView->model());
    if (NULL != old_geo_model)
    {
    old_geo_model->clear();
    }
geoTableView->setModel(new QSqlTableModel);
delete old_geo_model;
old_geo_model = NULL;

geo_data_set = false;

// Other view
QSqlTableModel * old_other_model = qobject_cast<QSqlTableModel *>(otherTableView->model());
    if (NULL != old_other_model)
    {
    old_other_model->clear();
    }
otherTableView->setModel(new QSqlTableModel);
delete old_other_model;
old_other_model = NULL;

other_data_set = false;
}

void MainWindow::delete_rows( QTableView * tView,
                              bool remove_files )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>(tView->model());
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = tView->selectionModel();
    if (NULL == selectionModel)
    {
    return;
    }
QModelIndexList currentSelection = selectionModel->selectedRows(0);
    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

QMessageBox mBox;
mBox.setWindowTitle( tr("Confirm") );
mBox.setIcon( QMessageBox::Question );
mBox.setText( tr("        Delete?" ) );
mBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    switch (mBox.exec())
    {
        case QMessageBox::No:
        return;
        break;

        default:
        break;
    }

QStringList file_names;
    if (true == remove_files)
    {
        for (int i = 0; i < currentSelection.size(); ++i)
        {
            if ( model->record( currentSelection.at(i).row() ).value("SAVED_AS").toString()  ==
                 QString( QLatin1String("LINK") ) )
            {
            file_names << model->record( currentSelection.at(i).row() ).value("FILE_NAME").toString();
            }
        }
    }

model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    for (int i = 0; i < currentSelection.size(); ++i)
    {
    bool success = model->removeRow( currentSelection.at(i).row() );
        if (true == success)
        {
        QString mes_rem = tr("Removed");
        mes_rem.append( QLatin1String(" ") );
        mes_rem.append( QString::number (currentSelection.at(i).row() ) );
        statusBar()->showMessage(mes_rem, 2000);
        qApp->processEvents();
        }
        else
        {
        statusBar()->showMessage( tr("The database reported : %1").arg(model->lastError().text() ),
                                  10000 );
        qApp->processEvents();
        }
    }

bool model_submit = model->submitAll();
    if ( true != model_submit )
    {
    QMessageBox::critical( this,
                           tr("Submit failed"),
                           tr("The database reported : %1").arg(model->lastError().text() ) );
    }
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();

}

void MainWindow::del_cat_row()
{
delete_rows( catTableView, false );
}

void MainWindow::del_auct_row()
{
delete_rows( auctTableView, false );
}

void MainWindow::del_geo_row()
{
delete_rows( geoTableView, false );
}

void MainWindow::del_other_row()
{
delete_rows( otherTableView, false );
}

void MainWindow::del_im_row()
{
delete_rows( imagesTableView, true );
previewLabel->clear();
iconObvLabel->clear();
iconRevLabel->clear();
iconEdgeLabel->clear();
qApp->processEvents();
show_icon("obverse");
show_icon("reverse");
show_icon("edge");
}

void MainWindow::del_doc_row()
{
delete_rows(docsTableView, true );
}

void MainWindow::show_contacts()
{
Contacts * contacts = new Contacts();
contacts->show();
}

void MainWindow::select_style()
{
StyleDialog * styleDialog = new StyleDialog;
styleDialog->show();
    if (styleDialog->exec() != QDialog::Accepted)
    {
    styleDialog->close();
    delete styleDialog;
    return;
    }
    else
    {
    QMap<QString, QString> m = styleDialog->return_selected();
    styleDialog->close();
    delete styleDialog;
    QSettings settings( QSettings::IniFormat,
                        QSettings::UserScope,
                        QApplication::organizationName(),
                        QApplication::applicationName() );
    settings.setFallbacksEnabled(false);
    settings.beginGroup( QLatin1String("GlobalSettings") );
    settings.setValue( QLatin1String("stylename"),
                       QVariant( m.value("style") ) );
    settings.setValue( QLatin1String("palette"),
                       QVariant( m.value("standard") ) );
    settings.endGroup();

    change_style( m.value("style"), m.value("standard") );
    }
}

void MainWindow::change_style(QString s, QString st)
{
    if (true == s.isEmpty() )
    {
    return;
    }
    else
    {
        if( s == QLatin1String("NorwegianWood") )
        {
        QApplication::setStyle(new NorwegianWoodStyle);
        }
        else
        {
        QApplication::setStyle(QStyleFactory::create(s));
        }

        if ( st == QLatin1String("TRUE") )
        {
        QApplication::setPalette(QApplication::style()->standardPalette());
        }
        else
        {
        QApplication::setPalette(originalPalette);
        }
    }
}

QSqlRecord MainWindow::construct_record(QString table_type,
                                        qint64 id)
{
QSqlRecord record = QSqlRecord();
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return record;
    }

    if ( table_type == QLatin1String("images") )
    {
    QString s = QLatin1String("select gen_id(");
    s.append(opened_album);
    s.append(QLatin1String("_images_gen, 1) from rdb$database"));
    qint64 image_id;
    image_id = Q_INT64_C(-1);
    QSqlQuery query(s, db);
        while (query.next())
        {
        image_id = query.value(0).toLongLong();
        }
    query.clear();
    record.insert( 0, QSqlField("IMAGE_ID", QVariant::LongLong) );
    record.insert( 1, QSqlField("COIN_ID", QVariant::LongLong) );
    record.insert( 2, QSqlField("FILE_NAME", QVariant::String) );
    record.insert( 3, QSqlField("SAVED_AS", QVariant::String) );
    record.insert( 4, QSqlField("RESERVED0", QVariant::String) );
    record.insert( 5, QSqlField("IS_EDGE_ICON", QVariant::Int) );
    record.insert( 6, QSqlField("IS_OBV_ICON", QVariant::Int) );
    record.insert( 7, QSqlField("IS_REV_ICON", QVariant::Int) );
    record.setValue("IMAGE_ID", image_id);
    record.setValue("COIN_ID", id);
    }
    else if ( table_type == QLatin1String("documents") )
    {
    QString s = QLatin1String("select gen_id(");
    s.append(opened_album);
    s.append(QLatin1String("_documents_gen, 1) from rdb$database"));
    qint64 doc_id;
    doc_id = Q_INT64_C(-1);
    QSqlQuery query(s, db);
        while (query.next())
        {
        doc_id = query.value(0).toLongLong();
        }
    query.clear();
    record.insert( 0, QSqlField("DOC_ID", QVariant::LongLong) );
    record.insert( 1, QSqlField("COIN_ID", QVariant::LongLong) );
    record.insert( 2, QSqlField("FILE_NAME", QVariant::String) );
    record.insert( 3, QSqlField("SAVED_AS", QVariant::String) );
    record.insert( 4, QSqlField("RESERVED0", QVariant::String) );
    record.setValue("DOC_ID", doc_id);
    record.setValue("COIN_ID", id);
    }
    else
    {
    }
return record;
}

bool MainWindow::check_index()
{
TabModel1 * alb_model =
        qobject_cast<TabModel1 *>(tableView->model());
    if (NULL == alb_model)
    {
    set_empty_view();
    return false;
    }

    if ( true != alb_model->hasIndex(0,0) )
    {
    set_empty_view();
    return false;
    }

    if ( true == opened_album.isEmpty() )
    {
    set_empty_view();
    return false;
    }

qint64 id = Q_INT64_C(-1);
qint64 view_record_id = Q_INT64_C(-1);
    if ( true != alb_model->record(view_index.row()).value("ID").isNull() )
    {
    id = alb_model->record(view_index.row()).value("ID").toLongLong();
    }

    if ( true != view_record.value("ID").isNull() )
    {
    view_record_id = view_record.value("ID").toLongLong();
    }
    else
    {
    set_empty_view();
    return false;
    }

    if (view_record_id == -1)
    {
    set_empty_view();
    return false;
    }

    if (id == -1)
    {
    set_empty_view();
    return false;
    }

return true;
}

void MainWindow::set_filter( bool f )
{
    if ( true == f )
    {
        {
        QSqlDatabase db = QSqlDatabase::database("collection", false);
            if ( !db.isOpen() )
            {
            QMessageBox::warning( this,
                                  tr("Error"),
                                  tr("Database is closed.") );
            close_db();
            return;
            }
        }

    FilterDialog * filterDialog = new FilterDialog( filter_,
                                                    collection_attrs,
                                                    asc_index_columns,
                                                    desc_index_columns );
    filterDialog->show();
        if (filterDialog->exec() != QDialog::Accepted)
        {
        setFilterButton->setChecked(false);
        filterDialog->close();
        delete filterDialog;
        return;
        }
        else
        {
        QString filter = filterDialog->return_filter();
        filter_ = filter;
        filterDialog->close();
        delete filterDialog;

            if ( true == filter_.isEmpty() )
            {
            setFilterButton->setChecked(false);
            return;
            }

        QSplashScreen * splash = new QSplashScreen( create_splash_image() );
        splash->show();
        splash->showMessage( tr("Loading ...") );
        qApp->processEvents();

        TabModel1 * model = qobject_cast<TabModel1 *>( tableView->model() );
            if (NULL != model)
            {
            model->setFilter(filter);
            model->select();
                if ( model->lastError().type() != QSqlError::NoError )
                {
                statusBar()->showMessage( model->lastError().text(), 10000 );
                }
            }

        splash->close();
        qApp->processEvents();
        delete splash;
        }
    }
    else
    {
    TabModel1 * model = qobject_cast<TabModel1 *>( tableView->model() );
        if ( NULL != model )
        {
        model->setFilter( QLatin1String("") );
        model->select();
            if (model->lastError().type() != QSqlError::NoError)
            {
            statusBar()->showMessage( model->lastError().text(), 10000 );
            }
        }
    }
set_empty_view();
}

void MainWindow::add_document()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Database is closed.") );
    close_db();
    return;
    }

bool chk = check_index();
    if( true != chk)
    {
    QMessageBox::critical( this,
                           "Error",
                           "Id check failed." );
    set_empty_view();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>( docsTableView->model() );
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

qint64 id = Q_INT64_C(-1);
id = view_record.value("ID").toLongLong();
    if ( id < 0 )
    {
    set_empty_view();
    return;
    }

QMap<QString, QString> m;
AddDocument * addDocument = new AddDocument(last_doc_dir);
addDocument->show();
    if ( addDocument->exec() != QDialog::Accepted )
    {
    addDocument->close();
    delete addDocument;
    return;
    }
    else
    {
    m = addDocument->return_selection();
    addDocument->close();
    delete addDocument;
    }

    if ( true == m.value("file_path").isEmpty() )
    {
    return;
    }

QString file_path = QDir::toNativeSeparators( m.value("file_path") );
QString f = m.value("file_name");
QSqlRecord record = construct_record( QLatin1String("documents"), id );
record.setValue( "SAVED_AS", m.value("file_type") );

last_doc_dir = m.value("last_doc_dir");

    if ( m.value("file_type") == QString( QLatin1String("BLOB") ) )
    {
    record.setValue("FILE_NAME", f);
    QFile file(file_path);
    file.open( QIODevice::ReadOnly );
    QByteArray byte_array = file.readAll();

    qint64 doc_id = Q_INT64_C(-1);
    doc_id = record.value("DOC_ID").toLongLong();

    QString s = QLatin1String("insert into ");
    s.append(opened_album);
    s.append( QLatin1String("_doc_blobs(doc_id,coin_id,doc_b) values (") );
    s.append( QString::number(doc_id) );
    s.append( QLatin1String(",") );
    s.append( QString::number(id) );
    s.append( QLatin1String(", :byte_array )") );
    QSqlQuery query(db);
    query.prepare(s);
    query.bindValue(":byte_array", QVariant(byte_array) );

    bool ok = false;
    ok = query.exec();
        if ( true != ok )
        {
        QMessageBox::critical( this,
                               tr("Query failed"),
                               tr("The database reported: %1").arg(db.lastError().text()) );
        query.clear();
        return;
        }

    query.clear();
    }
    else if ( m.value("file_type") == QString( QLatin1String("LINK") ) )
    {
    record.setValue("FILE_NAME", file_path);
    }
    else
    {
    }

bool success = model->insertRecord( -1, record );
    if ( true != success )
    {
    QMessageBox::critical( this,
                           tr("Update failed"),
                           tr("The database reported : %1").arg(model->lastError().text()) );
    //model->revertAll();
    model->select();
    set_empty_view();
    return;
    }

bool submit = model->submitAll();
    if ( true != submit )
    {
    QMessageBox::critical( this,
                           tr("Submit failed"),
                           tr("The database reported : %1").arg(model->lastError().text()));
    //model->revertAll();
    model->select();
    set_empty_view();
    return;
    }

model->select();
    if ( model->lastError().type() != QSqlError::NoError )
    {
    statusBar()->showMessage( model->lastError().text(), 10000 );
    }
}

void MainWindow::add_image()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Database is closed.") );
    close_db();
    return;
    }

bool chk = check_index();
    if( true != chk)
    {
    QMessageBox::critical( this,
                           "Debug",
                           "Id check failed." );
    set_empty_view();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>( imagesTableView->model() );
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

qint64 id = Q_INT64_C(-1);
id = view_record.value("ID").toLongLong();
    if (id < 0)
    {
    QMessageBox::critical( this,
                           "Error",
                           "Invalid id." );
    set_empty_view();
    return;
    }

QMap<QString, QString> m;
AddImage * addImage = new AddImage(last_im_dir);
addImage->show();
    if (addImage->exec() != QDialog::Accepted)
    {
    addImage->close();
    delete addImage;
    return;
    }
    else
    {
    m = addImage->return_selection();
    addImage->close();
    delete addImage;
    }

    if ( m.value("file_path").isEmpty() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Empty path.") );
    return;
    }

last_im_dir = m.value("last_im_dir");
QString file_path = m.value("file_path");
QString f = m.value("file_name");
QString ext = f.section(".", -1);
QSqlRecord record = construct_record(QLatin1String("images"), id);
record.setValue("SAVED_AS", m.value("file_type") );
qint64 image_id = Q_INT64_C(-1);
image_id = record.value("IMAGE_ID").toLongLong();

    if ( m.value("file_type") == QString( QLatin1String("BLOB") ) )
    {
    record.setValue("FILE_NAME", f);
    QFile file(file_path);
    file.open(QIODevice::ReadOnly);
    QImage i;
    QByteArray byte_array = file.readAll();

    bool blob_loaded = false;
        if ( ext == QLatin1String("svg") || ext == QLatin1String("SVG") )
        {
        blob_loaded = i.loadFromData(byte_array, "svg");
        }
        else
        {
        blob_loaded = i.loadFromData(byte_array);
        }

        if (true == blob_loaded)
        {
        int i_height = i.height();
        int i_width = i.width();
            if ( i_height > 8192 ||
                 i_width > 8192 )
            {
            QString size_message = tr("The image you are loading is ");
            size_message.append( QString::number(i_width) );
            size_message.append( QLatin1String("x") );
            size_message.append( QString::number(i_height) );
            size_message.append( QLatin1String(".") );

            QMessageBox::warning( this,
                                  tr("Warning"),
                                  size_message );
            }
        QPixmap p;
        p = QPixmap::fromImage( i.scaled( 250, 250, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
        QString p_key = opened_album;
        p_key.append( QLatin1String("_") );
        p_key.append( QString::number(image_id) );
        QPixmapCache::insert(p_key, p);
        previewLabel->setPixmap(p);
        }
        else
        {
        QString message = tr("Failed to load image.");
        QMessageBox::warning( this,
                              tr("Warning"),
                              message );
        }

        if ( m.value("resol") != QLatin1String("original") )
        {
        int image_size = -1;
            if ( m.value("resol") == QLatin1String("250") )
            {
            image_size = 250;
            }
            else if ( m.value("resol") == QLatin1String("400") )
            {
            image_size = 400;
            }
            else if ( m.value("resol") == QLatin1String("800") )
            {
            image_size = 800;
            }
            else if ( m.value("resol") == QLatin1String("1024") )
            {
            image_size = 1024;
            }

            if ( image_size != -1)
            {
            QImage scaled_i = QImage(i.scaled( image_size,
                                     image_size,
                                     Qt::KeepAspectRatio,
                                     Qt::SmoothTransformation ) );
            i = QImage();
            byte_array = QByteArray();
            QBuffer buffer(&byte_array);
            buffer.open(QIODevice::WriteOnly);
            bool ok = false;

            const char * format_p;
            QByteArray a = ext.toLatin1();
            format_p = a.constData();

                if ( ext.isEmpty() || ext.isNull() )
                {
                QMessageBox::critical( this,
                                       tr("Error"),
                                       tr("Can not scale, undefined extension.") );
                previewLabel->clear();
                return;
                }

            ok = scaled_i.save(&buffer, format_p);
                if ( true != ok )
                {
                QMessageBox::critical( this,
                                       tr("Error"),
                                       tr("Failed to write scaled image to buffer.") );
                previewLabel->clear();
                return;
                }

            }
        }

    QString s = QLatin1String("insert into ");
    s.append(opened_album);
    s.append( QLatin1String("_im_blobs(image_id,coin_id,image_b) values (") );
    s.append( QString::number(image_id) );
    s.append( QLatin1String(",") );
    s.append( QString::number(id) );
    s.append( QLatin1String(", :byte_array )") );
    QSqlQuery query(db);
    query.prepare(s);
    query.bindValue(":byte_array", QVariant(byte_array) );

    bool query_ok = false;
    query_ok = query.exec();
        if (true != query_ok)
        {
        QMessageBox::critical(this,
                             tr("Query failed"),
                             tr("The database reported: %1").arg(db.lastError().text()) );
        query.clear();
        previewLabel->clear();
        return;
        }

    query.clear();
    }
    else if ( m.value("file_type") == QString( QLatin1String("LINK") ) )
    {
    record.setValue("FILE_NAME", QDir::toNativeSeparators(file_path) );

    QImage i;
    int i_height = i.height();
    int i_width = i.width();
    i.load(file_path);
        if ( i_height > 8192 ||
             i_width > 8192 )
        {
        QString size_message = tr("The image you are loading is ");
        size_message.append( QString::number(i_width) );
        size_message.append( QLatin1String("x") );
        size_message.append( QString::number(i_height) );
        size_message.append( QLatin1String(".") );

        QMessageBox::warning( this,
                              tr("Warning"),
                              size_message );
        }

    QPixmap p;
    p = QPixmap::fromImage( i.scaled( 250, 250, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
    QString p_key = opened_album;
    p_key.append( QLatin1String("_") );
    p_key.append( QString::number(image_id) );
    QPixmapCache::insert(p_key, p);
    previewLabel->setPixmap(p);
    }
    else if ( m.value("file_type") == QString( QLatin1String("URL") ) )
    {
    record.setValue("FILE_NAME", file_path);
        if ( lang == QString( QLatin1String("ru") ) )
        {
        previewLabel->setPixmap( QPixmap(":/binary/no_preview_ru.png") );
        }
        else
        {
        previewLabel->setPixmap( QPixmap(":/binary/no_preview_en.png") );
        }
    }

bool success = model->insertRecord( -1, record );
    if (true != success)
    {
    QMessageBox::critical( this,
                           tr("Update failed"),
                           tr("The database reported : %1").arg(model->lastError().text()) );
    //model->revertAll();
    model->select();
    set_empty_view();
    return;
    }

bool submit = model->submitAll();
    if (true != submit)
    {
    QMessageBox::critical( this,
                           tr("Submit failed"),
                           tr("The database reported : %1").arg(model->lastError().text()));
    //model->revertAll();
    model->select();
    set_empty_view();
    return;
    }

model->select();
    if ( model->lastError().type() != QSqlError::NoError )
    {
    statusBar()->showMessage( model->lastError().text(), 10000 );
    }
}

void MainWindow::im_index_selected( QModelIndex index )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>(imagesTableView->model());
    if ( NULL == model )
    {
    previewLabel->clear();
    return;
    }

QSqlRecord record = QSqlRecord( model->record( index.row() ) );
QString file_name = record.value("FILE_NAME").toString();

QFileInfo fi(file_name);
QString name = fi.fileName();
QString ext = fi.suffix();

qint64 image_id = Q_INT64_C(-1);
image_id = record.value("IMAGE_ID").toLongLong();

    if ( true == record.value("SAVED_AS").isNull() ||
         image_id == -1 )
    {
    previewLabel->clear();
    return;
    }

QPixmap cached;
QString cached_key = opened_album;
cached_key.append( QLatin1String("_") );
cached_key.append( QString::number(image_id) );
bool found_in_cache = false;
found_in_cache = QPixmapCache::find(cached_key, cached);

    if ( true == found_in_cache )
    {
    previewLabel->setPixmap( cached );
    return;
    }

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
    {
    QByteArray ba;
    QString s = QLatin1String("select image_b from ");
    s.append(opened_album);
    s.append( QLatin1String("_im_blobs where image_id = ") );
    s.append( QString::number( record.value("IMAGE_ID").toLongLong() ) );
    QSqlQuery query(s, db);
        while (query.next())
        {
        ba = query.value(0).toByteArray();
        }
    query.clear();
    QImage i;
    bool blob_loaded = false;
        if ( ext == QLatin1String("svg") || ext == QLatin1String("SVG") )
        {
        blob_loaded = i.loadFromData(ba, "svg");
        }
        else
        {
        blob_loaded = i.loadFromData(ba);
        }
    ba.clear();
        if (true == blob_loaded)
        {
        QPixmap p;
        p = QPixmap::fromImage( i.scaled( 250, 250, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
        QString p_key = opened_album;
        p_key.append( QLatin1String("_") );
        p_key.append( QString::number(image_id) );
        QPixmapCache::insert(p_key, p);
        previewLabel->setPixmap(p);
        }
        else
        {
        statusBar()->showMessage( tr("Failed to load BLOB.") );
        previewLabel->clear();
        }
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("LINK") ) )
    {
        if (true != file_name.isEmpty() )
        {
        bool loaded = false;
        QImage i;
        i.load(file_name);
            if ( ext == QLatin1String("svg") || ext == QLatin1String("SVG") )
            {
            loaded = i.load(file_name, "svg");
            }
            else
            {
            loaded = i.load(file_name);
            }

            if ( true != loaded )
            {
            QString load_mes = tr("Failed to load file.");
            load_mes.append( QLatin1String(" " ) );
            load_mes.append(file_name);
            statusBar()->showMessage( load_mes, 10000 );
            previewLabel->clear();
            }
            else
            {
            QPixmap p = QPixmap::fromImage( i.scaled( 250, 250, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
            QString p_key = opened_album;
            p_key.append( QLatin1String("_") );
            p_key.append( QString::number(image_id) );
            QPixmapCache::insert(p_key, p);
            previewLabel->setPixmap(p);
            }
        }
        else
        {
        previewLabel->clear();
        }
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("URL") ) )
    {
        if ( lang == QString( QLatin1String("ru") ) )
        {
        previewLabel->setPixmap( QPixmap(":/binary/no_preview_ru.png") );
        }
        else
        {
        previewLabel->setPixmap( QPixmap(":/binary/no_preview_en.png") );
        }
    }
}

void MainWindow::tab_ind_changed(int ind)
{
    if (ind == 1)
    {
    QItemSelectionModel * selectionModel = tableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
    QModelIndexList currentSelection = selectionModel->selectedRows(0);
        if ( true == currentSelection.isEmpty() )
        {
        set_empty_view();
        return;
        }
        else
        {
        bool chk = check_index();
            if (true == chk)
            {
                if ( true == itemTabWidget->isEnabled() )
                {
                    if ( itemTabWidget->currentIndex() == 0 )
                    {
                        if ( true != icons_data_set )
                        {
                        show_icon( QLatin1String("obverse") );
                        show_icon( QLatin1String("reverse") );
                        show_icon( QLatin1String("edge") );
                        }
                    }
                    else if ( itemTabWidget->currentIndex() == 1 )
                    {
                        if ( true != desc_data_set )
                        {
                        show_desc();
                        }
                    }
                    else if ( itemTabWidget->currentIndex() == 2 )
                    {
                        if ( binaryTabWidget->currentIndex() == 0 )
                        {
                            if ( true != images_data_set )
                            {
                            set_data( opened_album, view_index, QLatin1String("images") );
                            }
                        }
                        else if ( binaryTabWidget->currentIndex() == 1 )
                        {
                            if ( true != documents_data_set )
                            {
                            set_data( opened_album, view_index, QLatin1String("documents") );
                            }
                        }
                        else
                        {
                        }
                    }
                    else if ( itemTabWidget->currentIndex() == 3 )
                    {
                        if ( referencesTabWidget->currentIndex() == 0 )
                        {
                            if ( true != catalogs_data_set )
                            {
                            set_data( opened_album, view_index, QLatin1String("catalogs") );
                            }
                        }
                        else if ( referencesTabWidget->currentIndex() == 1 )
                        {
                            if ( true != auctions_data_set )
                            {
                            set_data( opened_album, view_index, QLatin1String("auctions") );
                            }
                        }
                        else if ( referencesTabWidget->currentIndex() == 2 )
                        {
                            if ( true != geo_data_set )
                            {
                            set_data( opened_album, view_index, QLatin1String("geo") );
                            }
                        }
                        else if ( referencesTabWidget->currentIndex() == 3 )
                        {
                            if ( true != other_data_set )
                            {
                            set_data( opened_album, view_index, QLatin1String("other") );
                            }
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                }
            }
            else
            {
            set_empty_view();
            return;
            }
        }
    }
    else if (ind == 0)
    {
    bool ok = check_index();
        if ( true != ok )
        {
        set_empty_view();
        return;
        }
    }
    else
    {
    }
}

void MainWindow::set_icon( QString side )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>(imagesTableView->model());
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

    if ( true != model->hasIndex( 0, 0 ) )
    {
    return;
    }

QItemSelectionModel * selectionModel = imagesTableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }

QModelIndexList currentSelection = selectionModel->selectedRows(0);
    if ( true == currentSelection.isEmpty() )
    {
    QMessageBox::information( this,
                              tr("Error"),
                              tr("No image selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Selection is invalid.") );
    return;
    }
QSqlRecord record = QSqlRecord( model->record( currentSelection.at(0).row() ) );
qint64 image_id = Q_INT64_C(-1);
qint64 coin_id = Q_INT64_C(-1);
QString saved_as;
image_id = record.value("IMAGE_ID").toLongLong();
coin_id = record.value("COIN_ID").toLongLong();
saved_as = record.value("SAVED_AS").toString();

    if ( saved_as == QString( QLatin1String("URL") ) )
    {
    QMessageBox::information( this,
                              tr("Information"),
                              tr("No preview for WWW images.") );
    model->select();
    return;
    }
    
    if ( side == QLatin1String("obverse") )
    {
    record.setValue("IS_OBV_ICON", 1);
    }
    else if ( side == QLatin1String("reverse") )
    {
    record.setValue("IS_REV_ICON", 1);
    }
    else if ( side == QLatin1String("edge") )
    {
    record.setValue("IS_EDGE_ICON", 1);
    }
    else
    {
    }

bool success = false;
success = model->setRecord( currentSelection.at(0).row(), record );
    if ( true != success )
    {
    QMessageBox::critical( this,
                           tr("Update failed"),
                           tr("The database reported : %1").arg(model->lastError().text()));
    model->select();
    return;
    }

bool model_submit = model->submitAll();
    if ( true != model_submit )
    {
    QMessageBox::critical( this,
                           tr("Submit failed"),
                           tr("The database reported : %1").arg(model->lastError().text()));
    model->revertAll();
    return;
    }

    QString s = QLatin1String("update ");
    s.append(opened_album);
    s.append( QLatin1String("_images set ") );
        if ( side == QLatin1String("obverse") )
        {
        s.append( QLatin1String("is_obv_icon") );
        }
        else if ( side == QLatin1String("reverse") )
        {
        s.append( QLatin1String("is_rev_icon") );
        }
        else if ( side == QLatin1String("edge") )
        {
        s.append( QLatin1String("is_edge_icon") );
        }
    s.append( QLatin1String(" = 0 where coin_id = ") );
    s.append( QString::number(coin_id) );
    s.append( QLatin1String(" and image_id != ") );
    s.append( QString::number(image_id) );
    QSqlQuery query(db);
    query.prepare(s);
    bool query_ok = false;
    query_ok = query.exec();
        if ( true != query_ok )
        {
        QMessageBox::critical( this,
                               tr("Query failed"),
                               tr("The database reported: %1").arg(db.lastError().text()) );
        }

    query.clear();
    model->select();
        if ( model->lastError().type() != QSqlError::NoError )
        {
        statusBar()->showMessage( model->lastError().text(), 10000 );
        }

bool ok = check_index();
    if (true == ok)
    {
    show_icon(side);
    }
}

void MainWindow::close_album()
{
    if ( true == setFilterButton->isChecked() )
    {
    setFilterButton->blockSignals(true);
    setFilterButton->setChecked(false);
    setFilterButton->blockSignals(false);
    }

TabModel1 * old_model = qobject_cast<TabModel1 *>( tableView->model() );
tableView->setModel( new TabModel1() );
    if ( NULL != old_model )
    {
    old_model->clear();
    }
delete old_model;
old_model = NULL;
opened_album = QLatin1String("");
opened_album_num = QLatin1String("");
opened_album_name = QLatin1String("");
albumNumLabel->clear();
albumNameLabel->clear();
set_empty_view();
update_actions(true);
}

void MainWindow::tab_ind_changed_binary( int ind )
{
    if ( ind == 0 )
    {
        if ( true != images_data_set )
        {
        set_data( opened_album, view_index, QLatin1String("images") );
        }
    }
    else if ( ind == 1 )
    {
        if ( true != documents_data_set )
        {
        set_data( opened_album, view_index, QLatin1String("documents") );
        }
    }
    else
    {
    }
}

void MainWindow::tab_ind_changed_refer( int ind )
{
    if ( ind == 0 )
    {
        if ( true != catalogs_data_set )
        {
        set_data( opened_album, view_index, QLatin1String("catalogs") );
        }
    }
    else if ( ind == 1 )
    {
        if ( true != auctions_data_set )
        {
        set_data( opened_album, view_index, QLatin1String("auctions") );
        }
    }
    else if ( ind == 2 )
    {
        if ( true != geo_data_set )
        {
        set_data( opened_album, view_index, QLatin1String("geo") );
        }
    }
    else if ( ind == 3 )
    {
        if ( true != other_data_set )
        {
        set_data( opened_album, view_index, QLatin1String("other") );
        }
    }
    else
    {
    }
}

void MainWindow::tab_ind_changed_rel( int ind )
{
    if ( ind == 0 )
    {
        if ( true != icons_data_set )
        {
        show_icon("obverse");
        show_icon("reverse");
        show_icon("edge");
        }
    }

    if (ind == 1)
    {
        if ( true != desc_data_set )
        {
        show_desc();
        }
    }

    if ( ind == 2 )
    {
        if ( binaryTabWidget->currentIndex() == 0 )
        {
            if ( true != images_data_set )
            {
            set_data( opened_album, view_index, QLatin1String("images") );
            }
        }
        else if ( binaryTabWidget->currentIndex() == 1 )
        {
            if ( true != documents_data_set )
            {
            set_data( opened_album, view_index, QLatin1String("documents") );
            }
        }
        else
        {
        }
    }
    else if ( ind == 3 )
    {
        if ( referencesTabWidget->currentIndex() == 0 )
        {
            if ( true != catalogs_data_set )
            {
            set_data( opened_album, view_index, QLatin1String("catalogs") );
            }
        }
        else if ( referencesTabWidget->currentIndex() == 1 )
        {
            if ( true != auctions_data_set )
            {
            set_data( opened_album, view_index, QLatin1String("auctions") );
            }
        }
        else if ( referencesTabWidget->currentIndex() == 2 )
        {
            if ( true != geo_data_set )
            {
            set_data( opened_album, view_index, QLatin1String("geo") );
            }
        }
        else if ( referencesTabWidget->currentIndex() == 3 )
        {
            if ( true != other_data_set )
            {
            set_data( opened_album, view_index, QLatin1String("other") );
            }
        }
        else
        {
        }
    }
}

void MainWindow::set_font()
{
bool ok = false;
QFont font = QFontDialog::getFont(&ok);
QString font_str = font.toString();
    if ( true == ok )
    {
    QApplication::setFont(font);
    }
    else
    {
    return;
    }

QMessageBox mBox;
mBox.setWindowTitle( tr("Application Font") );
mBox.setIcon( QMessageBox::Question );
mBox.setText( tr("        Save?") );
mBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No );
    switch ( mBox.exec() )
    {
        case QMessageBox::Yes:
        break;

        default:
        return;
        break;
    }
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);
settings.beginGroup( QLatin1String("GlobalSettings") );
settings.setValue( QLatin1String("font"), QVariant( font_str ) );
settings.endGroup();

}

void MainWindow::show_icon(QString side)
{
qint64 coin_id = view_record.value("ID").toLongLong();
QString s =
QLatin1String("select coin_id, file_name, image_id, saved_as from ");
s.append(opened_album);
s.append( QLatin1String("_images where coin_id  = ") );
s.append( QString::number(coin_id) );
    if ( side == QLatin1String("obverse") )
    {
    s.append( QLatin1String(" and is_obv_icon = 1") );
    }
    else if ( side == QLatin1String("reverse") )
    {
    s.append( QLatin1String(" and is_rev_icon = 1") );
    }
    else if ( side == QLatin1String("edge") )
    {
    s.append( QLatin1String(" and is_edge_icon = 1") );
    }

QString saved_as;
QString file_name;
QString ext;
qint64 image_id = Q_INT64_C(-1);

QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QSqlQuery query(s, db);
    while (query.next())
    {
    coin_id = query.value(0).toLongLong();
    file_name = query.value(1).toString();
    image_id = query.value(2).toLongLong();
    saved_as = query.value(3).toString();
    }
query.clear();
ext = file_name.section(".", -1);

QPixmap cached;
QString cached_key = opened_album;
cached_key.append( QLatin1String("_") );
cached_key.append( QString::number(image_id) );
    if ( side == QLatin1String("edge") )
    {
    cached_key.append( QLatin1String("_e") );
    }

bool found_in_cache = false;
found_in_cache = QPixmapCache::find(cached_key, cached);

    if ( true == found_in_cache )
    {
        if ( side == QLatin1String("reverse") )
        {
        iconRevLabel->setPixmap(cached);
        }
        else if ( side == QLatin1String("obverse") )
        {
        iconObvLabel->setPixmap(cached);
        }
        else if ( side == QLatin1String("edge") )
        {
        iconEdgeLabel->setPixmap(cached);
        }
    return;
    }

    if ( saved_as == QString( QLatin1String("BLOB") ) )
    {
    QByteArray ba;
    QString s = QLatin1String("select image_b from ");
    s.append(opened_album);
    s.append( QLatin1String("_im_blobs where image_id = ") );
    s.append( QString::number(image_id) );
    QSqlQuery query(s, db);
        while (query.next())
        {
        ba = query.value(0).toByteArray();
        }
    query.clear();
    QImage i;
    bool blob_loaded = false;
        if ( ext == "svg" || ext == "SVG" )
        {
        blob_loaded = i.loadFromData(ba, "svg");
        }
        else
        {
        blob_loaded = i.loadFromData(ba);
        }

        if (true == blob_loaded)
        {
            if ( side == QLatin1String("obverse") )
            {
            QPixmap p;
            p = QPixmap::fromImage( i.scaled( 250, 250, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
            QString p_key = opened_album;
            p_key.append( QLatin1String("_") );
            p_key.append( QString::number(image_id) );
            QPixmapCache::insert(p_key, p);
            iconObvLabel->setPixmap(p);
            }
            else if ( side == QLatin1String("reverse") )
            {
            QPixmap p;
            p = QPixmap::fromImage( i.scaled( 250, 250, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
            QString p_key = opened_album;
            p_key.append( QLatin1String("_") );
            p_key.append( QString::number(image_id) );
            QPixmapCache::insert(p_key, p);
            iconRevLabel->setPixmap(p);
            }
            else if ( side == QLatin1String("edge") )
            {
            QPixmap p;
            p = QPixmap::fromImage( i.scaled( 506, 70, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
            QString p_key = opened_album;
            p_key.append( QLatin1String("_") );
            p_key.append( QString::number(image_id) );
            p_key.append( QLatin1String("_e") );
            QPixmapCache::insert(p_key, p);
            iconEdgeLabel->setPixmap(p);
            }
            else
            {
            }
        }
        else
        {
        statusBar()->showMessage( tr("Failed to load BLOB."), 10000 );
            if ( side == QLatin1String("obverse") )
            {
            iconObvLabel->clear();
            }
            else if ( side == QLatin1String("reverse") )
            {
            iconRevLabel->clear();
            }
            else if ( side == QLatin1String("edge") )
            {
            iconEdgeLabel->clear();
            }
            else
            {
            }
        }
    }
    else if ( saved_as == QString( QLatin1String("LINK") ) )
    {
        if ( true != file_name.isEmpty() )
        {
        QImage i;

        bool loaded = false;
            if ( ext == "svg" || ext == "SVG" )
            {
            loaded = i.load( file_name, "svg" );
            }
            else
            {
            loaded = i.load(file_name);
            }

            if ( true != loaded )
            {
            QString load_mes = tr("Failed to load file.");
            load_mes.append( QLatin1String(" " ) );
            load_mes.append(file_name);
            statusBar()->showMessage( load_mes, 10000 );
            }
            else
            {
                if ( side == QLatin1String("obverse") )
                {
                QPixmap p;
                p = QPixmap::fromImage( i.scaled( 250, 250, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
                QString p_key = opened_album;
                p_key.append( QLatin1String("_") );
                p_key.append( QString::number(image_id) );
                QPixmapCache::insert(p_key, p);
                iconObvLabel->setPixmap(p);
                }
                else if ( side == QLatin1String("reverse") )
                {
                QPixmap p;
                p = QPixmap::fromImage( i.scaled( 250, 250, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
                QString p_key = opened_album;
                p_key.append( QLatin1String("_") );
                p_key.append( QString::number(image_id) );
                QPixmapCache::insert(p_key, p);
                iconRevLabel->setPixmap(p);
                }
                else if ( side == QLatin1String("edge") )
                {
                QPixmap p;
                p = QPixmap::fromImage( i.scaled( 506, 70, Qt::KeepAspectRatio, Qt::SmoothTransformation) );
                QString p_key = opened_album;
                p_key.append( QLatin1String("_") );
                p_key.append( QString::number(image_id) );
                p_key.append( QLatin1String("_e") );
                QPixmapCache::insert(p_key, p);
                iconEdgeLabel->setPixmap(p);
                }
                else
                {
                }
            }
        }
    }
    else
    {
    }

icons_data_set = true;
}

void MainWindow::set_obverse_icon()
{
set_icon("obverse");
}

void MainWindow::set_reverse_icon()
{
set_icon("reverse");
}

void MainWindow::set_edge_icon()
{
set_icon("edge");
}

void MainWindow::album_attr()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }
QPixmap p = create_splash_image();
QSplashScreen splash(p);
splash.show();
splash.showMessage( tr("Loading ...") );
qApp->processEvents();
CollAttr * collAttr = new CollAttr();
connect(collAttr,
        SIGNAL( reload_attrs() ),
        this,
        SLOT( load_attrs() ) );
collAttr->show();

splash.finish(collAttr);
}

void MainWindow::load_attrs()
{
collection_attrs.clear();
collection_attrs["denominations"] = attr_query( QLatin1String("nom"),
                                       QLatin1String("noms_reg") );
collection_attrs["states"] = attr_query( QLatin1String("state"),
                                         QLatin1String("states_reg") );
collection_attrs["epochs"] = attr_query( QLatin1String("epoch"),
                                         QLatin1String("epochs_reg") );
collection_attrs["marks"] = attr_query( QLatin1String("mark"),
                                        QLatin1String("marks_reg") );
collection_attrs["materials"] = attr_query( QLatin1String("material"),
                                           QLatin1String("materials_reg") );
collection_attrs["edgeids"] = attr_query( QLatin1String("edgeid"),
                                          QLatin1String("edgeids_reg") );
collection_attrs["mints"] = attr_query( QLatin1String("mint"),
                                        QLatin1String("mints_reg") );
collection_attrs["types"] = attr_query( QLatin1String("obj_type"),
                                        QLatin1String("types_reg") );
collection_attrs["undertypes"] = attr_query( QLatin1String("undertype"),
                                             QLatin1String("undertypes_reg") );
collection_attrs["statuses"] = attr_query( QLatin1String("status"),
                                         QLatin1String("status_reg") );
collection_attrs["units"] = attr_query( QLatin1String("unit"),
                                        QLatin1String("units_reg") );
collection_attrs["currencies"] = attr_query( QLatin1String("currency"),
                                           QLatin1String("currency_reg") );
collection_attrs["conditions"] = attr_query( QLatin1String("condition"),
                                             QLatin1String("conditions_reg") );
collection_attrs["cert_auths"] = attr_query( QLatin1String("cert_auth"),
                                            QLatin1String("cert_auths_reg") );
collection_attrs["locations"] = attr_query( QLatin1String("location_name"),
                                            QLatin1String("locations_reg") );
collection_attrs["catalogs"] = attr_query( QLatin1String("catalog_name"),
                                           QLatin1String("catalogs_reg") );
collection_attrs["obvsymbs"] = attr_query( QLatin1String("obvsymb"),
                                           QLatin1String("obvsymbs_reg") );
collection_attrs["revsymbs"] = attr_query( QLatin1String("revsymb"),
                                           QLatin1String("revsymbs_reg") );
collection_attrs["obvtypes"] = attr_query( QLatin1String("obvtype"),
                                           QLatin1String("obvtypes_reg") );
collection_attrs["revtypes"] = attr_query( QLatin1String("revtype"),
                                           QLatin1String("revtypes_reg") );
collection_attrs["auctions"] = attr_query( QLatin1String("auction"),
                                           QLatin1String("auctions_reg") );
collection_attrs["rectypes"] = attr_query( QLatin1String("rectype"),
                                           QLatin1String("rectypes_reg") );
}

QStringList MainWindow::attr_query(QString column_name,
                                   QString table_string )
{
QStringList sl;
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return sl;
    }

QString s = QLatin1String("select ");
s.append(column_name);
s.append( QLatin1String(" from ") );
s.append(table_string);
s.append( QLatin1String(" order by 1 asc") );

QSqlQuery query(s, db);
    while (query.next())
    {
    sl << query.value(0).toString();
    }
query.clear();

return sl;
}

void MainWindow::show_image_double_clicked(QModelIndex index)
{
show_image( true,
            QLatin1String("opengl viewer"),
            index );
}

void MainWindow::show_image_rmb()
{
show_image( false,
            QLatin1String("opengl viewer"),
            QModelIndex() );
}

void MainWindow::show_image_button()
{
show_image( false,
            QLatin1String("opengl viewer"),
            QModelIndex() );
}

void MainWindow::show_image( bool double_clicked,
                             QString viewer_type,
                             QModelIndex index )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>(imagesTableView->model());
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = imagesTableView->selectionModel();
    if ( NULL == selectionModel )
    {
    return;
    }

QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord();

    if ( true != double_clicked )
    {
    unsigned int y = 0;
        for ( int i = 0; i < currentSelection.size(); ++i )
        {
            if ( y == 2 )
            {
            break;
            }
        y += 1;
        }
    record = QSqlRecord( model->record( currentSelection.at(0).row() ) );
    }
    else
    {
    record = QSqlRecord( model->record( index.row() ) );
    }

QString file_name = record.value("FILE_NAME").toString();
QString ext = file_name.section(".", -1);
QPixmap pm;

    if (true == record.value("SAVED_AS").isNull() ||
        true == record.value("FILE_NAME").isNull() )
    {
    return;
    }

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
    {
    QByteArray ba;
    QString s = QLatin1String("select image_b from ");
    s.append(opened_album);
    s.append( QLatin1String("_im_blobs where image_id = ") );
    s.append( QString::number( record.value("IMAGE_ID").toLongLong() ) );
    QSqlQuery query(s, db);
        while (query.next())
        {
        ba = query.value(0).toByteArray();
        }
    query.clear();

    bool blob_loaded = false;
        if ( ext == QLatin1String("svg") || ext == QLatin1String("SVG") )
        {
        blob_loaded = pm.loadFromData(ba, "svg");
        }
        else
        {
        blob_loaded = pm.loadFromData(ba);
        }
    ba.clear();

        if (true == blob_loaded)
        {
            if ( viewer_type == QLatin1String("opengl viewer") )
            {
            GraphicsView * view = new GraphicsView( 0,
                                                    gl_tested,
                                                    max_size);
            view->set_image(pm);
            view->show();
            QObject::connect( view,
                              SIGNAL( return_gl_tested(bool, int) ),
                              this,
                              SLOT( update_gl_tested(bool, int) ) );
            }
            else
            {
            }
        }
        else
        {
        QMessageBox::warning( this,
                              tr("Warning"),
                              tr("Failed to load BLOB.") );
        }
    pm = QPixmap();
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("LINK") ) )
    {
        if ( true != file_name.isEmpty() )
        {
        pm.load(file_name);

            if (viewer_type == QLatin1String("opengl viewer") )
            {
            GraphicsView * view = new GraphicsView( 0,
                                                    gl_tested,
                                                    max_size);
            view->set_image(pm);
            view->show();
            QObject::connect( view,
                              SIGNAL( return_gl_tested(bool, int) ),
                              this,
                              SLOT( update_gl_tested(bool, int) ) );
            }
            else
            {
            }
        }
    pm = QPixmap();
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("URL") ) )
    {
    QUrl url = QUrl(file_name.trimmed() );
        if ( true != url.isValid() ||
             true == url.host().isEmpty() )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("URL is invalid.") );	    
        return;
        }    
    Download * download = new Download( url, QString ( QLatin1String("show") ) );
    QObject::connect( download,
                      SIGNAL( download_finished( Download *,
                                                 bool,
                                                 QString,
                                                 QString,
                                                 QString ) ),
                      this,
                      SLOT( get_download( Download *,
                                          bool,
                                          QString,
                                          QString,
                                          QString ) ) );
    }

}

void MainWindow::save_image_as()
{
QImage i;
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>(imagesTableView->model());
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = imagesTableView->selectionModel();
    if ( NULL == selectionModel )
    {
    return;
    }

QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord( model->record( currentSelection.at(0).row() ) );
QString file_name = record.value("FILE_NAME").toString();
QString ext = file_name.section(".", -1);
QByteArray ba;

    if ( true == record.value("SAVED_AS").isNull() ||
         true == record.value("FILE_NAME").isNull() )
    {
    return;
    }

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
    {
    statusBar()->showMessage( tr("Loading image from BLOB ...") );
    qApp->processEvents();
    QString s = QLatin1String("select image_b from ");
    s.append(opened_album);
    s.append( QLatin1String("_im_blobs where image_id = ") );
    s.append( QString::number( record.value("IMAGE_ID").toLongLong() ) );
    QSqlQuery query(s, db);
        while (query.next())
        {
        ba = query.value(0).toByteArray();
        }
    query.clear();
    statusBar()->showMessage( tr("Loading image from BLOB ... Done."), 3000 );
    qApp->processEvents();
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("URL") ) )
    {
    QFileInfo fi( file_name.trimmed() );
    QUrl url( file_name.trimmed() );
        if ( true != url.isValid() ||
             true == url.host().isEmpty() )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("URL is invalid.") );	    
        return;
        }

    QString sugg_path = QLatin1String("");
        if ( true == last_image_save_dir.isEmpty() )
        {
        sugg_path.append( QDir::homePath() );
        }
        else
        {
        sugg_path = last_image_save_dir;
        }
    
        if ( true != fi.fileName().isEmpty() )
        {
        sugg_path.append( QDir::separator() );
        sugg_path.append( fi.fileName().trimmed() );
        }
    
    QString f = QFileDialog::getSaveFileName( this,
                                      tr("Select File"),
                                      sugg_path,
                                      QString() );
        if ( true != f.isEmpty() )
        {
        Download * download = new Download( url,
                                            QString ( QLatin1String("save") ),
                                            QDir::toNativeSeparators(f) );
        QObject::connect( download,
                          SIGNAL( download_finished( Download *,
                                                     bool,
                                                     QString,
                                                     QString,
                                                     QString ) ),
                          this,
                          SLOT( get_download( Download *,
                                              bool,
                                              QString,
                                              QString,
                                              QString ) ) );        
        }
    return;
    }

SaveAsDialog * d = new SaveAsDialog( file_name,
                                     last_image_save_dir );
d->show();
QMap<QString, QVariant> m;
    if ( d->exec() != QDialog::Accepted )
    {
    d->close();
    delete d;
    return;
    }
    else
    {
    m = d->return_data();
    d->close();
    delete d;
    }

    if ( true == m.value("new_file").toString().isEmpty() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("File name is invalid.") );
    return;
    }

    if ( true == m.value("folder_name").toString().isEmpty() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Directory is invalid.") );
    last_image_save_dir = QLatin1String("");
    return;
    }
    else
    {
    last_image_save_dir = m.value("folder_name").toString();
    }

QString save_path_ = m.value("folder_name").toString();
save_path_.append( QString( QDir::separator() ) );
save_path_.append( m.value("new_file").toString() );
QString save_path = QDir::toNativeSeparators(save_path_);

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("LINK") ) )
    {
        if ( true != test_files( file_name, save_path ) )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Source and destination are the same file.") );
        return;
        }
    }

// no changes

    if ( m.value("format_changed").toString() == QLatin1String("F")
         &&
         m.value("resize").toString() == QLatin1String("F") )
    {
        if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
        {
        bool success = false;
        success = write_byte_array(save_path, ba);
            if ( true != success )
            {
            QMessageBox::critical(this,
                                  tr("Error"),
                                  tr("Could not save image.") );
            }
        }
        else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("LINK") ) )
        {
        bool success = false;
        QFile f__(file_name);
            if ( true == QFile::exists(save_path) )
            {
            QMessageBox mBox;
            mBox.setWindowTitle( tr("File exists") );
            mBox.setIcon( QMessageBox::Question );
            mBox.setText( tr("        Overwrite?") );
            mBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No );
                switch ( mBox.exec() )
                {
                    case QMessageBox::Yes:
                    break;

                    default:
                    return;
                    break;
                }

            QFile save_path__(save_path);
            save_path__.open(QIODevice::WriteOnly);
            save_path__.remove();
            }

        success = QFile::copy(file_name, save_path);
            if (!success)
            {
            QMessageBox::critical( this,
                                   tr("Error"),
                                   tr("Could not save image.") );
            }
        }
    return;
    }

// image changed

QString image_ext = record.value("FILE_NAME").toString().section(".", -1);

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
    {
    bool success = false;
        if ( image_ext == QLatin1String("svg") || image_ext == QLatin1String("SVG") )
        {
        success = i.loadFromData(ba, "svg");
        }
        else
        {
        success = i.loadFromData(ba);
        }

        if (true != success)
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Can not load image from BLOB.") );
        return;
        }
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("LINK") ) )
    {
    bool success = false;
        if ( image_ext == QLatin1String("svg") || image_ext == QLatin1String("SVG") )
        {
        success =  i.load(file_name, "svg");
        }
        else
        {
        success =  i.load(file_name);
        }

        if (true != success)
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Can not load image from file.") );
        return;
        }
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("URL") ) )
    {
    return;
    }
    else
    {
    return;
    }

// resize

QImage j;

    if ( m.value("resize").toString() == QLatin1String("T")
         &&
         true != m.value("side").toString().isEmpty() )
    {
        if ( m.value("side").toString() == tr("Height") )
        {
            if ( m.value("size").toInt() > 0 )
            {
            j = QImage( i.scaledToHeight( m.value("size").toInt(),
                                          Qt::SmoothTransformation) );
            }
        }
        else if ( m.value("side").toString() == tr("Width") )
        {
            if ( m.value("size").toInt() > 0 )
            {
            j = QImage( i.scaledToWidth( m.value("size").toInt(),
                                         Qt::SmoothTransformation) );
            }
        }
        else
        {
        }
    }
    else
    {
    j = QImage(i);
    }

i = QImage();

QFile file_(save_path);
    if ( file_.exists() )
    {
    QMessageBox mBox;
    mBox.setWindowTitle( tr("File exists") );
    mBox.setIcon( QMessageBox::Question );
    mBox.setText( tr("        Overwrite?") );
    mBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        switch (mBox.exec())
        {
            case QMessageBox::Yes:
            break;

            default:
            return;
            break;
        }

    file_.open(QIODevice::WriteOnly);
    bool t = file_.remove();
        if (true != t)
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Failed to remove file.") );
        return;
        }
    }

// format and compression

int quality = 85;
const char * format_p;

    if ( m.value("format_changed").toString() == QLatin1String("T") )
    {
    bool success = false;
    quality = 85;
    QByteArray a = m.value("new_format").toString().toLatin1();
    format_p = a.constData();

        if ( m.value("compr_changed").toString() == QLatin1String("T") )
        {
        quality = m.value("new_quality").toInt();
        success = j.save(save_path, format_p, quality);
        }
        else
        {
        success = j.save(save_path, format_p);
        }

        if (true != success)
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Failed to save image.") );
        }
    }
    else
    {
    bool success = false;
    QByteArray a = save_path.section(".", -1).toLatin1();
    format_p = a.constData();
        if ( m.value("compr_changed").toString() == QLatin1String("T") )
        {
        quality = m.value("new_quality").toInt();
        success = j.save( save_path, format_p, quality );
        }
        else
        {
        success = j.save( save_path, format_p);
        }

        if ( true != success )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Failed to save image.") );
        }
    }
}

void MainWindow::show_charts()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

bool filter_set = false;
    if ( true == setFilterButton->isChecked() )
    {
    filter_set = true;
        if ( true == filter_.isEmpty() )
        {
        filter_set = false;
        }
    }

QMap<QString, QString> m;
SelectCollectionDialog * d = new SelectCollectionDialog( collection_attrs.value("statuses"),
                                                         filter_set );
d->show();
    if ( d->exec() != QDialog::Accepted )
    {
    d->close();
    delete d;
    return;
    }
    else
    {
    m = d->return_selected();
    d->close();
    delete d;
    }

QString table;
QString num;
QString name;
QString filter = QLatin1String("");

    if ( m.value("use_current") == QLatin1String("TRUE") )
    {
    table = opened_album;
    num = opened_album_num;
    name = opened_album_name;
    }
    else
    {
        if ( true == m.value("table").isEmpty() )
        {
        return;
        }
    table = m.value("table");
    num = m.value("num");
    name = m.value("name");
    }

    if ( m.value("items") == QLatin1String("ALL") )
    {
    }
    else if ( m.value("items") == QLatin1String("FILTER") )
    {
    filter = filter_;
    }
    else if ( m.value("items") == QLatin1String("STATUS") )
    {
        if ( true == m.value("status").isEmpty() )
        {
        return;
        }
        else
        {
        filter = QLatin1String(" status = ");
        filter.append( QString(QChar(0x27)) );
        filter.append( m.value("status") );
        filter.append( QString(QChar(0x27)) );
        }
    }
    else
    {
    }

QSplashScreen splash( create_splash_image() );
splash.show();
qApp->processEvents();
ChartWidget * chartWidget = new ChartWidget( table,
                                             num,
                                             name,
                                             filter,
                                             asc_index_columns,
                                             desc_index_columns );
chartWidget->show();
splash.finish(chartWidget);
}

void MainWindow::set_next()
{
TabModel1 * model = qobject_cast<TabModel1 *>( tableView->model() );
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

int next_index = view_index.row() + 1;
QSqlRecord record = model->record(next_index);

    if ( true == record.isEmpty() ||
         true == record.isNull("ID") )
    {
    nextButton->setEnabled(false);
    backButton->setEnabled(true);
    return;
    }

delete_binary_models();
delete_references_models();
previewLabel->clear();
iconObvLabel->clear();
iconRevLabel->clear();
iconEdgeLabel->clear();
icons_data_set = false;
desc_data_set = false;
descTextEdit->blockSignals(true);
descTextEdit->clear();
descTextEdit->blockSignals(false);
textChangedLabel->clear();
saveTextLabel->clear();
nextButton->setEnabled(true);
backButton->setEnabled(true);
QModelIndex index = QModelIndex( model->index( next_index, 0 ) );

    if ( true == index.isValid() )
    {
    view_index = QModelIndex(index);
    view_record = QSqlRecord(record);
    set_view(view_index);
        if ( true == itemTabWidget->isEnabled() )
        {
            if ( itemTabWidget->currentIndex() == 0 )
            {
            show_icon( QLatin1String("obverse") );
            show_icon( QLatin1String("reverse") );
            show_icon( QLatin1String("edge") );
            }
            else if ( itemTabWidget->currentIndex() == 1 )
            {
            show_desc();
            }
            else if ( itemTabWidget->currentIndex() == 2 )
            {
                if ( binaryTabWidget->currentIndex() == 0 )
                {
                    if ( true != images_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("images") );
                    }
                }
                else if ( binaryTabWidget->currentIndex() == 1 )
                {
                    if ( true != documents_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("documents") );
                    }
                }
                else
                {
                }
            }
            else if ( itemTabWidget->currentIndex() == 3 )
            {
                if ( referencesTabWidget->currentIndex() == 0 )
                {
                    if ( true != catalogs_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("catalogs") );
                    }
                }
                else if ( referencesTabWidget->currentIndex() == 1 )
                {
                    if ( true != auctions_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("auctions") );
                    }
                }
                else if ( referencesTabWidget->currentIndex() == 2 )
                {
                    if ( true != geo_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("geo") );
                    }
                }
                else if ( referencesTabWidget->currentIndex() == 3 )
                {
                    if ( true != other_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("other") );
                    }
                }
                else
                {
                }
            }
        }
    tableView->selectRow(next_index);
    }

}

void MainWindow::set_back()
{
TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

int prev_index = view_index.row() - 1;
QSqlRecord record = model->record(prev_index);
    if ( prev_index < 0 )
    {
    backButton->setEnabled(false);
    nextButton->setEnabled(true);
    return;
    }

    if ( true == record.isEmpty() ||
         true == record.isNull( QString("ID") ) )
    {
    backButton->setEnabled(false);
    nextButton->setEnabled(true);
    return;
    }

delete_binary_models();
delete_references_models();
previewLabel->clear();
iconObvLabel->clear();
iconRevLabel->clear();
iconEdgeLabel->clear();
icons_data_set = false;
desc_data_set = false;
descTextEdit->blockSignals(true);
descTextEdit->clear();
descTextEdit->blockSignals(false);
textChangedLabel->clear();
saveTextLabel->clear();

    if ( prev_index == 0 )
    {
    backButton->setEnabled(false);
    nextButton->setEnabled(true);
    }
    else
    {
    backButton->setEnabled(true);
    nextButton->setEnabled(true);
    }

QModelIndex index = QModelIndex( model->index( prev_index, 0 ) );
    if ( true == index.isValid() )
    {
    view_index = QModelIndex(index);
    view_record = QSqlRecord(record);
    set_view(view_index);
        if ( true == itemTabWidget->isEnabled() )
        {
            if ( itemTabWidget->currentIndex() == 0 )
            {
            show_icon( QLatin1String("obverse") );
            show_icon( QLatin1String("reverse") );
            show_icon( QLatin1String("edge") );
            }
            else if ( itemTabWidget->currentIndex() == 1 )
            {
            show_desc();
            }
            else if ( itemTabWidget->currentIndex() == 2 )
            {
                if ( binaryTabWidget->currentIndex() == 0 )
                {
                    if ( true != images_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("images") );
                    }
                }
                else if ( binaryTabWidget->currentIndex() == 1 )
                {
                    if ( true != documents_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("documents") );
                    }
                }
                else
                {
                }
            }
            else if ( itemTabWidget->currentIndex() == 3 )
            {
                if ( referencesTabWidget->currentIndex() == 0 )
                {
                    if ( true != catalogs_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("catalogs") );
                    }
                }
                else if ( referencesTabWidget->currentIndex() == 1 )
                {
                    if ( true != auctions_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("auctions") );
                    }
                }
                else if ( referencesTabWidget->currentIndex() == 2 )
                {
                    if ( true != geo_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("geo") );
                    }
                }
                else if ( referencesTabWidget->currentIndex() == 3 )
                {
                    if ( true != other_data_set )
                    {
                    set_data( opened_album, view_index, QLatin1String("other") );
                    }
                }
                else
                {
                }
            }
        }
    tableView->selectRow(prev_index);
    }

}

bool MainWindow::write_byte_array( QString file_name,
                                   QByteArray ba )
{
    if ( file_name.isEmpty() )
    {
    return false;
    }

QFile file_(file_name);
    if ( file_.exists() )
    {
    QMessageBox mBox;
    mBox.setWindowTitle( tr("File exists") );
    mBox.setIcon( QMessageBox::Question );
    mBox.setText( tr("Overwrite?") );
    mBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No );
        switch ( mBox.exec() )
        {
            case QMessageBox::Yes:
            break;

            default:
            return false;
            break;
        }
    file_.open(QIODevice::WriteOnly);
    file_.remove();
    }
QFile file(file_name);
bool opened = file.open(QIODevice::WriteOnly);
    if (true != opened)
    {
    return false;
    }
qint64 bytes = Q_INT64_C(-1);
bytes = file.write(ba);
QString message = tr("Wrote");
message.append( QLatin1String(" ") );
message.append( QString::number(bytes) );
message.append( QLatin1String(" ") );
message.append( tr("bytes") );
statusBar()->showMessage(message, 5000);
bool success = file.flush();
file.close();
return success;
}

void MainWindow::save_doc_as()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>(docsTableView->model());
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = docsTableView->selectionModel();
    if ( NULL == selectionModel )
    {
    return;
    }

QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord( model->record( currentSelection.at(0).row() ) );
QByteArray ba;
QString path = QLatin1String("");

    if ( true == record.value("SAVED_AS").isNull() ||
         true == record.value("FILE_NAME").isNull() )
    {
    return;
    }

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
    {
    statusBar()->showMessage( tr("Loading document from BLOB ...") );
    qApp->processEvents();
    QString s = QLatin1String("select doc_b from ");
    s.append(opened_album);
    s.append( QLatin1String("_doc_blobs where doc_id = ") );
    s.append( QString::number( record.value("DOC_ID").toLongLong() ) );
    QSqlQuery query(s, db);
        while (query.next())
        {
        ba = query.value(0).toByteArray();
        }
    query.clear();
    statusBar()->showMessage( tr("Loading document from BLOB ... Done.") );
    qApp->processEvents();
    }


SaveDocDialog * d = new SaveDocDialog();
d->set_file_name( record.value("FILE_NAME").toString() );
d->show();
    if (d->exec() != QDialog::Accepted)
    {
    d->close();
    delete d;
    return;
    }
    else
    {
    path = d->return_data();
    d->close();
    delete d;
    }

    if ( true == path.isEmpty() )
    {
    QMessageBox::critical(this,
                         tr("Error"),
                         tr("Path invalid.") );
    return;
    }

QString path_ = QDir::toNativeSeparators(path);
QString file_name = record.value("FILE_NAME").toString();

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
    {
    bool success = false;
    success = write_byte_array(path_, ba);
        if ( true != success )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Could not save image.") );
        }
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("LINK") ) )
    {

        if ( true != test_files( file_name, path_ ) )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Source and destination are the same file.") );
        return;
        }

    bool success = false;

        if ( true == QFile::exists(path_) )
        {
        QMessageBox mBox;
        mBox.setWindowTitle( tr("File exists") );
        mBox.setIcon( QMessageBox::Question );
        mBox.setText( tr("Overwrite?") );
        mBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No );
            switch ( mBox.exec() )
            {
                case QMessageBox::No:
                return;
                break;

                default:
                break;
            }
        QFile path__(path_);
        path__.open(QIODevice::WriteOnly);
        path__.remove();
        }

    success = QFile::copy( file_name, path_ );
        if ( true != success )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Could not save document.") );
        }
    }
}

void MainWindow::show_full_obv()
{
QString side = QLatin1String("obverse");
QString viewer_type = QLatin1String("opengl viewer");
show_full( side, viewer_type );
}

void MainWindow::show_full_rev()
{
QString side = QLatin1String("reverse");
QString viewer_type = QLatin1String("opengl viewer");
show_full( side, viewer_type );
}

void MainWindow::show_full_edge()
{
QString side = QLatin1String("edge");
QString viewer_type = QLatin1String("opengl viewer");
show_full( side, viewer_type );
}

void MainWindow::show_full( QString side, QString viewer_type )
{
    if ( true == view_record.isNull("ID") )
    {
    QMessageBox::critical( this,
                           "Error",
                           "ID is NULL." );
    return;
    }
qint64 id = Q_INT64_C(-1);
id = view_record.value("ID").toLongLong();

QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QString s1 = QLatin1String("select image_id, file_name, saved_as from ");
s1.append(opened_album);
s1.append( QLatin1String("_images where ") );
    if (side == "obverse")
    {
    s1.append( QLatin1String("is_obv_icon") );
    }
    else if (side == "reverse")
    {
    s1.append( QLatin1String("is_rev_icon") );
    }
    else if (side == "edge")
    {
    s1.append( QLatin1String("is_edge_icon") );
    }

s1.append( QLatin1String(" = 1 and coin_id = ") );
s1.append( QString::number(id) );

qint64 image_id = Q_INT64_C(-1);
QString file_name = QLatin1String("");
QString saved_as = QLatin1String("");

QSqlQuery query1(s1, db);
    while ( query1.next() )
    {
    image_id = query1.value(0).toLongLong();
    file_name = query1.value(1).toString();
    saved_as = query1.value(2).toString();
    }
query1.clear();

QString ext = file_name.section(".", -1);
QPixmap pixmap;

    if ( saved_as == QString( QLatin1String("BLOB") ) )
    {
    QByteArray ba;
    QString s2 = QLatin1String("select image_b from ");
    s2.append(opened_album);
    s2.append( QLatin1String("_im_blobs ") );
    s2.append( QLatin1String("where image_id = ") );
    s2.append( QString::number(image_id) );
    QSqlQuery query2(s2, db);
        while ( query2.next() )
        {
        ba = query2.value(0).toByteArray();
        }
    query2.clear();

    bool blob_loaded = false;
        if ( ext == QLatin1String("svg") || ext == QLatin1String("SVG") )
        {
        blob_loaded = pixmap.loadFromData( ba, "svg" );
        }
        else
        {
        blob_loaded = pixmap.loadFromData(ba);
        }
     ba.clear();
        if (true == blob_loaded)
        {
            if (viewer_type == QLatin1String("opengl viewer") )
            {
            GraphicsView * view = new GraphicsView( 0,
                                                    gl_tested,
                                                    max_size);
            view->set_image(pixmap);
            view->show();
            QObject::connect( view,
                              SIGNAL( return_gl_tested(bool, int) ),
                              this,
                              SLOT( update_gl_tested(bool, int) ) );
            }
            else
            {
            }
        }
        else
        {
        QMessageBox::warning( this,
                              tr("Warning"),
                              tr("Failed to load image.") );
        }
    pixmap = QPixmap();
    }
    else if ( saved_as == QString( QLatin1String("LINK") ) )
    {
        if ( true != file_name.isEmpty() )
        {
        bool loaded = false;
        loaded = pixmap.load(file_name);
            if ( true != loaded )
            {
            QString mes_load = tr("Failed to load file.");
            mes_load.append( QLatin1String(" ") );
            mes_load.append(file_name);
            statusBar()->showMessage( mes_load, 10000 );
            }

            if (viewer_type == QLatin1String("opengl viewer") )
            {
            GraphicsView * view = new GraphicsView( 0,
                                                    gl_tested,
                                                    max_size);
            view->set_image(pixmap);
            view->show();
            QObject::connect( view,
                              SIGNAL( return_gl_tested(bool, int) ),
                              this,
                              SLOT( update_gl_tested(bool, int) ) );
            }
            else
            {
            }
        }
    pixmap = QPixmap();
    }
    else if ( saved_as == QString( QLatin1String("URL") ) )
    {
    QUrl url = QUrl(file_name.trimmed() );
        if ( true != url.isValid() ||
             true == url.host().isEmpty() )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("URL is invalid.") );	    
        return;
        }
    Download * download = new Download( url, QString ( QLatin1String("show") ) );
    QObject::connect( download,
                      SIGNAL( download_finished( Download *,
                                                 bool,
                                                 QString,
                                                 QString,
                                                 QString ) ),
                      this,
                      SLOT( get_download( Download *,
                                          bool,
                                          QString,
                                          QString,
                                          QString ) ) );    
    }

}

void MainWindow::show_desc()
{
descTextEdit->blockSignals(true);
descTextEdit->clear();

QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

qint64 id = Q_INT64_C(-1);
    if ( true == view_record.isNull("ID") )
    {
    return;
    }
id = view_record.value("ID").toLongLong();

QString s = QLatin1String("select desc_b from ");
s.append(opened_album);
s.append( QLatin1String("_desc_blobs where coin_id = ") );
s.append( QString::number(id) );
QSqlQuery query(s, db);
QByteArray ba;
    while ( query.next() )
    {
    ba = query.value(0).toByteArray();
    }
query.clear();
QString t = QString::fromUtf8( ba.constData() );

descTextEdit->setAcceptRichText(false);
descTextEdit->setPlainText(t);

textChangedLabel->clear();
saveTextLabel->clear();

descTextEdit->blockSignals(false);

desc_data_set = true;
}

void MainWindow::save_desc()
{
bool check = check_index();
    if ( true != check )
    {
    return;
    }

QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

qint64 id = Q_INT64_C(-1);
    if ( true == view_record.isNull("ID") )
    {
    return;
    }
id = view_record.value("ID").toLongLong();

QString s = QLatin1String("select count(1) from ");
s.append(opened_album);
s.append( QLatin1String("_desc_blobs where coin_id = ") );
s.append( QString::number(id) );
QSqlQuery query1(s, db);
int i = -1;
    while ( query1.next() )
    {
    i = query1.value(0).toInt();
    }
query1.clear();
    if ( i == -1)
    {
    return;
    }

descTextEdit->setAcceptRichText(false);
QString t = descTextEdit->toPlainText();

QByteArray ba = t.toUtf8();
QVariant v = QVariant(ba);
QSqlQuery query(db);

    if ( i == 0 )
    {
    QString q = QLatin1String("insert into ");
    q.append(opened_album);
    q.append( QLatin1String("_desc_blobs (coin_id, desc_b) values(") );
    q.append( QString::number(id) );
    q.append( QLatin1String(", :byte_array )") );
    query.prepare(q);
    query.bindValue(":byte_array", v);
    }
    else if (i == 1)
    {
    QString q = QLatin1String("update ");
    q.append(opened_album);
    q.append( QLatin1String("_desc_blobs set desc_b = ? where coin_id = ") );
    q.append( QString::number(id) );
    query.prepare(q);
    query.bindValue(0, v);
    }
    else
    {
    return;
    }

bool r = false;
r = query.exec();
query.clear();

    if (true != r)
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Update failed.") );
    return;
    }

textChangedLabel->clear();
saveTextLabel->clear();
}

void MainWindow::show_codecs()
{
QSplashScreen * s = new QSplashScreen( create_splash_image() );
Codecs * c = new Codecs;
c->show();
    if ( c->exec() != QDialog::Accepted )
    {
    c->close();
    delete c;
    return;
    }
    else
    {
    s->show();
    qApp->processEvents();
    descTextEdit->setAcceptRichText(false);
    descTextEdit->insertPlainText( c->return_decoded() );
    s->close();
    qApp->processEvents();
    c->close();
    delete c;
    }
delete s;
}

void MainWindow::switch_to_ru(bool t)
{
    if (true != t)
    {
    actionRussian->setChecked(true);
    return;
    }

    if (appTranslator != NULL)
    {
    qApp->removeTranslator(appTranslator);
    delete appTranslator;
    appTranslator = NULL;
    }

    if (qtTranslator != NULL)
    {
    qApp->removeTranslator(qtTranslator);
    delete qtTranslator;
    qtTranslator = NULL;
    }

appTranslator = new QTranslator();
appTranslator->load(":/superapp_ru");
qtTranslator = new QTranslator();
qtTranslator->load(":/binary/qt_ru");
qApp->installTranslator(appTranslator);
qApp->installTranslator(qtTranslator);
//actionZh->setChecked(false);
actionEnglish->setChecked(false);
actionGerman->setChecked(false);
lang = QLatin1String("ru");
retranslateUi(this);
}

void MainWindow::remember_ru( bool t )
{
    if ( true == t )
    {
    QString language = QLatin1String("ru");
    QSettings settings( QSettings::IniFormat,
                        QSettings::UserScope,
                        QApplication::organizationName(),
                        QApplication::applicationName() );
    settings.setFallbacksEnabled(false);
    settings.beginGroup( QLatin1String("GlobalSettings") );
    settings.setValue( QLatin1String("language"),
                       QVariant(language) );
    settings.endGroup();
    }
}

void MainWindow::switch_to_en(bool t)
{
    if (true != t)
    {
    actionEnglish->setChecked(true);
    return;
    }

    if (appTranslator != NULL)
    {
    qApp->removeTranslator(appTranslator);
    delete appTranslator;
    appTranslator = NULL;
    }

    if (qtTranslator != NULL)
    {
    qApp->removeTranslator(qtTranslator);
    delete qtTranslator;
    qtTranslator = NULL;
    }
appTranslator = new QTranslator();
qtTranslator = new QTranslator();
qApp->installTranslator(appTranslator);
qApp->installTranslator(qtTranslator);
actionRussian->setChecked(false);
//actionZh->setChecked(false);
actionGerman->setChecked(false);
lang = QLatin1String("en");
retranslateUi(this);
}

void MainWindow::remember_en( bool t )
{
    if ( true == t )
    {
    QString language = QLatin1String("en");
    QSettings settings( QSettings::IniFormat,
                        QSettings::UserScope,
                        QApplication::organizationName(),
                        QApplication::applicationName() );
    settings.setFallbacksEnabled(false);
    settings.beginGroup( QLatin1String("GlobalSettings") );
    settings.setValue( QLatin1String("language"),
                       QVariant(language) );
    settings.endGroup();
    }
}

void MainWindow::switch_to_de(bool t)
{
    if (true != t)
    {
    actionGerman->setChecked(true);
    return;
    }

    if (appTranslator != NULL)
    {
    qApp->removeTranslator(appTranslator);
    delete appTranslator;
    appTranslator = NULL;
    }

    if (qtTranslator != NULL)
    {
    qApp->removeTranslator(qtTranslator);
    delete qtTranslator;
    qtTranslator = NULL;
    }
appTranslator = new QTranslator();
appTranslator->load(":/superapp_de");
qtTranslator = new QTranslator();
qtTranslator->load(":/binary/qt_de");
qApp->installTranslator(appTranslator);
qApp->installTranslator(qtTranslator);
actionRussian->setChecked(false);
actionEnglish->setChecked(false);
//actionZh->setChecked(false);
lang = QLatin1String("de");
retranslateUi(this);
}

void MainWindow::remember_de( bool t )
{
    if ( true == t )
    {
    QString language = QLatin1String("de");
    QSettings settings( QSettings::IniFormat,
                        QSettings::UserScope,
                        QApplication::organizationName(),
                        QApplication::applicationName() );
    settings.setFallbacksEnabled(false);
    settings.beginGroup( QLatin1String("GlobalSettings") );
    settings.setValue( QLatin1String("language"),
                       QVariant(language) );
    settings.endGroup();
    }
}


/*
void MainWindow::switch_to_zh_CN(bool t)
{
    if (true != t)
    {
    actionZh->setChecked(true);
    return;
    }

    if (appTranslator != NULL)
    {
    qApp->removeTranslator(appTranslator);
    delete appTranslator;
    appTranslator = NULL;
    }

    if (qtTranslator != NULL)
    {
    qApp->removeTranslator(qtTranslator);
    delete qtTranslator;
    qtTranslator = NULL;
    }
appTranslator = new QTranslator();
appTranslator->load(":/superapp_zh_CN");
qtTranslator = new QTranslator();
qtTranslator->load(":/binary/qt_zh_CN");
qApp->installTranslator(appTranslator);
qApp->installTranslator(qtTranslator);
actionRussian->setChecked(false);
actionEnglish->setChecked(false);
actionGerman->setChecked(false);
lang = QLatin1String("zh_CN");
retranslateUi(this);
}

void MainWindow::remember_zh_CN( bool t )
{
    if ( true == t )
    {
    QString language = QLatin1String("zh_CN");
    QSettings settings( QSettings::IniFormat,
                        QSettings::UserScope,
                        QApplication::organizationName(),
                        QApplication::applicationName() );
    settings.setFallbacksEnabled(false);
    settings.beginGroup( QLatin1String("GlobalSettings") );
    settings.setValue( QLatin1String("language"),
                       QVariant(language) );
    settings.endGroup();
    }
}
*/

void MainWindow::add_cat_row()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error" ),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

    if ( view_record.isNull("ID") )
    {
    return;
    }

qint64 coin_id = view_record.value("ID").toLongLong();

CatRowWidget * w = new CatRowWidget(collection_attrs);
w->new_record( coin_id, opened_album );
w->show();
QObject::connect( w,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, QLatin1String, bool ) ),
                  this,
                  SLOT( commit_rel( QSqlRecord, QModelIndex,  QLatin1String, bool ) ) );
return;
}

void MainWindow::edit_cat_row()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error"),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>( catTableView->model() );
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = catTableView->selectionModel();
        if ( NULL == selectionModel )
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord( model->record( currentSelection.at(0).row() ) );

CatRowWidget * w = new CatRowWidget(collection_attrs);
w->set_record( record, currentSelection.at(0) );
w->show();
QObject::connect( w,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, QLatin1String, bool ) ),
                  this,
                  SLOT( commit_rel( QSqlRecord, QModelIndex, QLatin1String, bool ) ) );
}

void MainWindow::add_auct_row()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error" ),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

    if ( view_record.isNull("ID") )
    {
    return;
    }

qint64 coin_id = view_record.value("ID").toLongLong();

AuctRowWidget * w = new AuctRowWidget(collection_attrs);
w->new_record( coin_id, opened_album );
w->show();
QObject::connect( w,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, QLatin1String, bool ) ),
                  this,
                  SLOT( commit_rel( QSqlRecord, QModelIndex,  QLatin1String, bool ) ) );
return;
}

void MainWindow::edit_auct_row()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error"),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>( auctTableView->model() );
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = auctTableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if ( currentSelection.isEmpty() )
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord( model->record(currentSelection.at(0).row() ) );

AuctRowWidget * w = new AuctRowWidget(collection_attrs);
w->set_record( record, currentSelection.at(0) );
w->show();
QObject::connect( w,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, QLatin1String, bool ) ),
                  this,
                  SLOT( commit_rel( QSqlRecord, QModelIndex, QLatin1String, bool ) ) );
}

void MainWindow::add_geo_row()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error" ),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

    if ( view_record.isNull("ID") )
    {
    return;
    }

qint64 coin_id = view_record.value("ID").toLongLong();

GeoRowWidget * w = new GeoRowWidget();
w->new_record( coin_id, opened_album );
w->show();
QObject::connect( w,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, QLatin1String, bool ) ),
                  this,
                  SLOT( commit_rel( QSqlRecord, QModelIndex,  QLatin1String, bool ) ) );
return;
}

void MainWindow::edit_geo_row()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error"),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>( geoTableView->model() );
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = geoTableView->selectionModel();
        if ( NULL == selectionModel )
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if ( currentSelection.isEmpty() )
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord( model->record( currentSelection.at(0).row() ) );

GeoRowWidget * w = new GeoRowWidget();
w->set_record( record, currentSelection.at(0) );
w->show();
QObject::connect( w,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, QLatin1String, bool ) ),
                  this,
                  SLOT( commit_rel( QSqlRecord, QModelIndex, QLatin1String, bool ) ) );
}

void MainWindow::add_other_row()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error" ),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

    if ( view_record.isNull("ID") )
    {
    return;
    }

qint64 coin_id = view_record.value("ID").toLongLong();

OtherRowWidget * w = new OtherRowWidget();
w->new_record( coin_id, opened_album );
w->show();
QObject::connect( w,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, QLatin1String, bool ) ),
                  this,
                  SLOT( commit_rel( QSqlRecord, QModelIndex,  QLatin1String, bool ) ) );
return;
}

void MainWindow::edit_other_row()
{
    {
    QSqlDatabase db = QSqlDatabase::database("collection", false);
        if ( true != db.isOpen() )
        {
        QMessageBox::warning( this,
                              tr("Error"),
                              tr("Database is closed.") );
        close_db();
        return;
        }
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>( otherTableView->model() );
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = otherTableView->selectionModel();
        if ( NULL == selectionModel )
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if ( currentSelection.isEmpty() )
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord( model->record( currentSelection.at(0).row() ) );

OtherRowWidget * w = new OtherRowWidget();
w->set_record( record, currentSelection.at(0) );
w->show();
QObject::connect( w,
                  SIGNAL( record_to_commit( QSqlRecord, QModelIndex, QLatin1String, bool ) ),
                  this,
                  SLOT( commit_rel( QSqlRecord, QModelIndex, QLatin1String, bool ) ) );
}

void MainWindow::cat_index_selected()
{
QSqlTableModel * model = qobject_cast<QSqlTableModel *>( catTableView->model() );

    if (NULL != model)
    {
    actionCatN->setDisabled(false);
        if ( true == catTableView->currentIndex().isValid() )
        {
        actionCatD->setDisabled(false);
        }
        else
        {
        actionCatD->setDisabled(true);
        }
    }
    else
    {
    actionCatN->setDisabled(true);
    actionCatE->setDisabled(true);
    actionCatD->setDisabled(true);
    }

QItemSelectionModel * selectionModel = catTableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

unsigned int y = 0;
    for (int i = 0; i < currentSelection.size(); ++i)
    {
        if (y == 2)
        {
        break;
        }
    y += 1;
    }

    if (y < 2)
    {
    actionCatE->setDisabled(false);
    }
    else
    {
    actionCatE->setDisabled(true);
    }
}

void MainWindow::auct_index_selected()
{
QSqlTableModel * model = qobject_cast<QSqlTableModel *>( auctTableView->model() );

    if (NULL != model)
    {
    actionAuctN->setDisabled(false);
        if ( true == auctTableView->currentIndex().isValid() )
        {
        actionAuctD->setDisabled(false);
        }
        else
        {
        actionAuctD->setDisabled(true);
        }
    }
    else
    {
    actionAuctN->setDisabled(true);
    actionAuctE->setDisabled(true);
    actionAuctD->setDisabled(true);
    }

QItemSelectionModel * selectionModel = auctTableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

unsigned int y = 0;
    for (int i = 0; i < currentSelection.size(); ++i)
    {
        if (y == 2)
        {
        break;
        }
    y += 1;
    }

    if (y < 2)
    {
    actionAuctE->setDisabled(false);
    }
    else
    {
    actionAuctE->setDisabled(true);
    }
}

void MainWindow::geo_index_selected()
{
QSqlTableModel * model = qobject_cast<QSqlTableModel *>( geoTableView->model() );

    if (NULL != model)
    {
    actionGeoN->setDisabled(false);
        if ( true == geoTableView->currentIndex().isValid() )
        {
        actionGeoD->setDisabled(false);
        }
        else
        {
        actionGeoD->setDisabled(true);
        }
    }
    else
    {
    actionGeoN->setDisabled(true);
    actionGeoE->setDisabled(true);
    actionGeoD->setDisabled(true);
    }

QItemSelectionModel * selectionModel = geoTableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

unsigned int y = 0;
    for (int i = 0; i < currentSelection.size(); ++i)
    {
        if (y == 2)
        {
        break;
        }
    y += 1;
    }

    if (y < 2)
    {
    actionGeoE->setDisabled(false);
    }
    else
    {
    actionGeoE->setDisabled(true);
    }
}

void MainWindow::other_index_selected()
{
QSqlTableModel * model = qobject_cast<QSqlTableModel *>( otherTableView->model() );

    if (NULL != model)
    {
    actionOtherN->setDisabled(false);
        if ( true == otherTableView->currentIndex().isValid() )
        {
        actionOtherD->setDisabled(false);
        }
        else
        {
        actionOtherD->setDisabled(true);
        }
    }
    else
    {
    actionOtherN->setDisabled(true);
    actionOtherE->setDisabled(true);
    actionOtherD->setDisabled(true);
    }

QItemSelectionModel * selectionModel = otherTableView->selectionModel();
        if (NULL == selectionModel)
        {
        return;
        }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

unsigned int y = 0;
    for (int i = 0; i < currentSelection.size(); ++i)
    {
        if (y == 2)
        {
        break;
        }
    y += 1;
    }

    if (y < 2)
    {
    actionOtherE->setDisabled(false);
    }
    else
    {
    actionOtherE->setDisabled(true);
    }
}

void MainWindow::commit_rel( QSqlRecord record,
                             QModelIndex index,
                             QLatin1String id,
                             bool new_item )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QSqlTableModel * model = NULL;
    if ( id == QLatin1String("CAT_ID") )
    {
    model = qobject_cast<QSqlTableModel *>( catTableView->model() );
    }
    else if ( id == QLatin1String("AUCT_ID") )
    {
    model = qobject_cast<QSqlTableModel *>( auctTableView->model() );
    }
    else if ( id == QLatin1String("SPOT_ID") )
    {
    model = qobject_cast<QSqlTableModel *>( geoTableView->model() );
    }
    else if ( id == QLatin1String("OTHER_ID") )
    {
    model = qobject_cast<QSqlTableModel *>( otherTableView->model() );
    }

    if ( model == NULL )
    {
    return;
    }

    if ( true == record.isNull("COIN_ID") )
    {
    return;
    }

    if ( true == record.isNull(id) )
    {
    return;
    }

bool success = false;
    if ( true == new_item )
    {
    success = model->insertRecord( -1, record );
    }
    else
    {
    success = model->setRecord( index.row(), record );
    }

    if (!success)
    {
    QMessageBox::critical( this,
                           tr("Update failed"),
                           tr("The database reported : %1").arg(model->lastError().text()));
    model->select();
    return;
    }

bool model_submit = model->submitAll();

    if (!model_submit)
    {
    QMessageBox::critical( this,
                           tr("Submit failed"),
                           tr("The database reported : %1").arg(model->lastError().text()));
    model->revertAll();
    return;
    }

    if (true == new_item)
    {
    model->setSort(0, Qt::DescendingOrder);
    model->select();
        if (model->lastError().type() != QSqlError::NoError)
        {
        statusBar()->showMessage( model->lastError().text(), 10000 );
        }

    QModelIndex zero_index = QModelIndex( model->index( 0, 0 ) );
        if ( true == zero_index.isValid() )
        {
            if ( id == QLatin1String("CAT_ID") )
            {
            catTableView->selectRow(0);
            }
            else if ( id == QLatin1String("AUCT_ID") )
            {
            auctTableView->selectRow(0);
            }
            else if ( id == QLatin1String("SPOT_ID") )
            {
            geoTableView->selectRow(0);
            }
            else if ( id == QLatin1String("OTHER_ID") )
            {
            otherTableView->selectRow(0);
            }
        }
    statusBar()->showMessage( tr("Update successed."), 2000 );
    }
    else
    {
    model->select();
        if (model->lastError().type() != QSqlError::NoError)
        {
        statusBar()->showMessage( model->lastError().text(), 10000 );
        }

    int idx = 0;
        while ( idx < index.row() )
        {
        model->fetchMore();
        idx += 256;
        }

        if ( true == (model->record(index.row()).value(id).toLongLong() ==
                      record.value(id).toLongLong() ) )
        {
            if ( id == QLatin1String("CAT_ID") )
            {
            catTableView->selectRow( index.row() );
            }
            else if ( id == QLatin1String("AUCT_ID") )
            {
            auctTableView->selectRow( index.row() );
            }
            else if ( id == QLatin1String("SPOT_ID") )
            {
            geoTableView->selectRow( index.row() );
            }
            else if ( id == QLatin1String("OTHER_ID") )
            {
            otherTableView->selectRow( index.row() );
            }
        statusBar()->showMessage( tr("Update successed."), 2000 );
        }
        else
        {
        QMessageBox::information( this,
                                  tr("Success"),
                                  tr("Update successed.\nNote: model's sorting has changed.") );
        }
    }
}

void MainWindow::update_gl_tested(bool tested, int size)
{
gl_tested = tested;
max_size = size;
}

void MainWindow::import_dialog()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Database is closed.") );
    close_db();
    return;
    }

QMap<QString, QString> sel_m;
XMLImportDialog * xd = new XMLImportDialog;
xd->show();
    if (xd->exec() != QDialog::Accepted)
    {
    xd->close();
    delete xd;
    return;
    }
    else
    {
    sel_m = xd->return_selected();
    xd->close();
    delete xd;
    }

    if ( sel_m.value("not_ready") == QLatin1String("TRUE") )
    {
    return;
    }

QString path = sel_m.value("file_path");
    if ( path.isEmpty() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Invalid path.") );
    return;
    }

QFile file(path);
    if ( !file.open( QFile::ReadOnly | QFile::Text ) )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Can not open file.") );
    return;
    }

QString dest_table =  sel_m.value("alb_table");
    if ( dest_table.isNull() ||
         dest_table.isEmpty() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Table name is empty.") );
    return;
    }

QString sheet = sel_m.value("file_sheet");
    if ( sheet.isNull() ||
         sheet.isEmpty() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Worksheet name is invalid.") );
    return;
    }

QPixmap p = create_splash_image();

QSplashScreen splash(p);
splash.show();
splash.showMessage( tr("Parsing MS XML Spreadsheet File") );
qApp->processEvents();

XMLParse handler(sheet);
QXmlSimpleReader reader;
reader.setContentHandler(&handler);
reader.setErrorHandler(&handler);

QXmlInputSource * xmlInputSource = new QXmlInputSource(&file);
QList< QMap<int, QString> > l;
    if ( true == reader.parse(xmlInputSource, false ) )
    {
    l = handler.return_data();
    }
    else
    {
    QString error = handler.errorString();
    QMessageBox::critical( this,
                           tr("Error"),
                           error  );
    return;
    }

delete xmlInputSource;
xmlInputSource = NULL;

QMap<int, int> columns_data;
int ignored_rows = 0;

XMLTableDialog * tw = new XMLTableDialog;
    if ( sel_m.value("ncat_export") == QLatin1String("TRUE") )
    {
    tw->set_model(l, true);
    }
    else
    {
    tw->set_model(l, false);
    }
tw->show();
splash.finish(tw);

    if (tw->exec() != QDialog::Accepted)
    {
    tw->close();
    delete tw;
    return;
    }
    else
    {
    columns_data = tw->return_columns();
    ignored_rows = tw->return_ignored_rows();
    tw->close();
    delete tw;
    }


Schema * schema = new Schema();
    if ( NULL == schema )
    {
    return;
    }

close_album();

int all_rows  = l.size() - ignored_rows;
ProgressDialog * pw = new ProgressDialog(all_rows);
pw->show();

blocking = 1;

int count = 0;

QString columns_str = schema->columns_for_query();
QMap<int, QString> column_names = schema->column_names();
int columns_count = schema->columns_count();
QList<int> doubles = schema->doubles();
QList<int> integers = schema->integers();
QList<int> bools = schema->bools();
QList<int> longlongs = schema->longlongs();
QList<int> strings = schema->strings();
QList<int> integer_dates = schema->integer_dates();

    for ( int y = ignored_rows; y < l.size(); y++ )
    {
    QMap<QString, QString> final_row;
    QMap<int, QString> raw_row;
    raw_row = l.value(y);

    count += 1;
    QString stat_message = tr("Processing row");
    stat_message.append( QLatin1String(" ") );
    stat_message.append( QString::number(count) );
    stat_message.append( QLatin1String(" / ") );
    stat_message.append( QString::number(all_rows) );
    stat_message.append( QLatin1String(".") );
    statusBar()->showMessage(stat_message, 2000);
    pw->set_value(count);
    qApp->processEvents();

        for ( int j = 1; j < columns_count; ++j )
        {
        int ind = columns_data.value(j, -1);
            if ( ind >= 0 )
            {
                if ( true == integer_dates.contains(j) )
                {
                QString str = raw_row.value(ind);
                QDate date = QDate::fromString(str, "yyyyMMdd");
                    if ( true == date.isValid() )
                    {
                    final_row[ column_names.value(j) ] = str;
                    }
                    else
                    {
                    final_row[ column_names.value(j) ] = QLatin1String("null");
                    }
                }
                else if ( true == integers.contains(j) )
                {
                QString str_raw = raw_row.value(ind);
                QRegExp rx("\\D");
                bool match = str_raw.contains(rx);
                    if ( true != match)
                    {
                    bool ok = false;
                    int num = str_raw.toInt( &ok, 10);
                        if ( true == ok )
                        {
                        final_row[ column_names.value(j) ] = QString::number(num);
                        }
                        else
                        {
                        final_row[ column_names.value(j) ] = QLatin1String("null");
                        }
                    }
                    else
                    {
                    final_row[ column_names.value(j) ] = QLatin1String("null");
                    }
                }
                else if ( true == doubles.contains(j) )
                {
                QString str_raw = raw_row.value(ind);
                bool ok = false;
                double num = str_raw.toDouble(&ok);
                    if ( true == ok )
                    {
                    final_row[ column_names.value(j) ] = QString::number(num);
                    }
                    else
                    {
                    final_row[ column_names.value(j) ] = QLatin1String("null");
                    }
                }
                else if ( true == longlongs.contains(j) )
                {
                QString str_raw = raw_row.value(ind);
                bool ok = false;
                qint64 num = Q_INT64_C(0);
                num = str_raw.toLongLong(&ok);
                    if ( true == ok )
                    {
                    final_row[ column_names.value(j) ] = QString::number(num);
                    }
                    else
                    {
                    final_row[ column_names.value(j) ] = QLatin1String("null");
                    }
                }
                else if ( true == bools.contains(j) )
                {
                QString str_raw = raw_row.value(ind);
                    if ( str_raw == QLatin1String("Y") ||
                         str_raw == QLatin1String("y") ||
                         str_raw == QLatin1String("1") ||
                         str_raw == QLatin1String("true") ||
                         str_raw == QLatin1String("True") ||
                         str_raw == QLatin1String("TRUE") )
                    {
                    QString str = QString(QChar(0x27));
                    str.append( QLatin1String("Y") );
                    str.append( QString(QChar(0x27)) );
                    final_row[ column_names.value(j) ] = str;
                    }
                    else
                    {
                    final_row[ column_names.value(j) ] = QLatin1String("null");
                    }
                }
                else
                {
                final_row[ column_names.value(j) ] = preprocess_varchar( raw_row.value(ind), j );
                }
            }
            else
            {
            final_row[ column_names.value(j) ] = QLatin1String("null");
            }
        }

    QString desc = QLatin1String("");
        for (int z = 1001; z <= 1257; z++ )
        {
        int desc_ind = columns_data.value(z, -1);
            if ( desc_ind > 0 )
            {
            QString s = QString(raw_row.value(desc_ind));
            QString ns = QLatin1String("");
                for (int x = 0; x < s.length(); x++)
                {
                QChar c(s.at(x));
                    if (c == QChar(0x27))
                    {
                    ns.append(c);
                    ns.append(c);
                    }
                    else
                    {
                    ns.append(c);
                    }
                }
            desc.append(ns);
            desc.append( QLatin1String("\n\n") );
            }
        }

        if ( true != desc.isEmpty() )
        {
        final_row["desc"] = desc;
        }

    qint64 id = Q_INT64_C(-1);
    QString query_id_str = QLatin1String("select gen_id(");
    query_id_str.append(dest_table);
    query_id_str.append(QLatin1String("_a_gen,1) from rdb$database"));
    QSqlQuery query_id(query_id_str, db);
        while (query_id.next())
        {
        id = query_id.value(0).toLongLong();
        }
    query_id.clear();

    QMap<int, QString> column_names = schema->column_names();

    QString s = QLatin1String("insert into ");
    s.append(dest_table);
    s.append( QLatin1String(" (") );
    s.append(columns_str);
    s.append( QLatin1String(") values (") );
    s.append( QString::number(id) );
    s.append( QLatin1String(",") );
    int last_column = column_names.size() - 1;
         for ( int z = 1; z <= last_column; ++z )
         {
         s.append( final_row.value( column_names.value(z) ) );
             if ( z != last_column )
             {
             s.append( QLatin1String(",") );
             }
         }
    s.append( QLatin1String(")") );
    QSqlQuery query(db);
    query.prepare(s);
    query.exec();
    query.clear();

    QString final_desc = final_row.value("desc");
        if ( true != final_desc.isEmpty() )
        {
        QByteArray desc_ba = final_desc.toUtf8();
        QString desc_str = QLatin1String("insert into ");
        desc_str.append(dest_table);
        desc_str.append( QLatin1String("_desc_blobs (coin_id, desc_b) values(") );
        desc_str.append( QString::number(id) );
        desc_str.append( QLatin1String(", :byte_array)") );
        QSqlQuery query_desc(db);
        query_desc.prepare(desc_str);
        query_desc.bindValue( ":byte_array", QVariant(desc_ba) );
        query_desc.exec();
        query_desc.clear();
        }
    }

blocking = 0;
qApp->processEvents();
pw->close();
delete pw;

l.clear();

delete schema;

set_album( sel_m.value("alb_table"),
           sel_m.value("alb_table_num"),
           sel_m.value("alb_table_name") );
sel_m.clear();
}

void MainWindow::image_to_clipboard()
{
QImage i;
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    close_db();
    return;
    }

QSqlTableModel * model = qobject_cast<QSqlTableModel *>( imagesTableView->model() );
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = imagesTableView->selectionModel();
    if (NULL == selectionModel)
    {
    return;
    }

QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Nothing is selected.") );
    return;
    }

    if ( true != currentSelection.at(0).isValid() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Index is invalid.") );
    return;
    }

QSqlRecord record = QSqlRecord( model->record( currentSelection.at(0).row() ) );
QString file_name = record.value("FILE_NAME").toString();
QString ext = file_name.section(".", -1);
QByteArray ba;

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
    {
    QString s = QLatin1String("select image_b from ");
    s.append(opened_album);
    s.append( QLatin1String("_im_blobs where image_id = ") );
    s.append( QString::number( record.value("IMAGE_ID").toLongLong() ) );
    QSqlQuery query(s, db);
        while (query.next())
        {
        ba = query.value(0).toByteArray();
        }
    query.clear();
    }

    if ( record.value("SAVED_AS").toString() == QString( QLatin1String("BLOB") ) )
    {
    bool success = false;
    success = i.loadFromData(ba);
        if (true != success)
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Can not load image.") );
        return;
        }
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("LINK") ) )
    {
    bool success = false;
    success =  i.load(file_name);
        if (true != success)
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("Can not load image.") );
        return;
        }
    }
    else if ( record.value("SAVED_AS").toString() == QString( QLatin1String("URL") ) )
    {
    QUrl url = QUrl(file_name.trimmed() );
        if ( true != url.isValid() ||
             true == url.host().isEmpty() )
        {
        QMessageBox::critical( this,
                               tr("Error"),
                               tr("URL is invalid.") );	    
        return;
        }
    Download * download = new Download( url, QString ( QLatin1String("copy") ) );
    QObject::connect( download,
                      SIGNAL( download_finished( Download *,
                                                 bool,
                                                 QString,
                                                 QString,
                                                 QString ) ),
                      this,
                      SLOT( get_download( Download *,
                                          bool,
                                          QString,
                                          QString,
                                          QString ) ) );    
    return;
    }

QMimeData * data = new QMimeData;
data->setImageData(i);
QClipboard * clipboard = QApplication::clipboard();
clipboard->setMimeData(data, QClipboard::Clipboard);
}

void MainWindow::delete_all_rows()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }
QString album = opened_album;
QString album_num = opened_album_num;
QString album_name = opened_album_name;

QString mess_str = tr("Delete EVERYTHING from Collection");
mess_str.append( QLatin1String(" ") );
mess_str.append(opened_album_num);
mess_str.append( QLatin1String(" ") );
mess_str.append(opened_album_name);
mess_str.truncate(128);

QMessageBox mBox;
mBox.setWindowTitle( tr("Confirm") );
mBox.setIcon( QMessageBox::Question );
mBox.setText(mess_str);

mBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    switch (mBox.exec())
    {
        case QMessageBox::Yes:
        break;

        default:
        return;
        break;
    }

QMessageBox mBox1;
mBox1.setWindowTitle( tr("Confirm Again") );
mBox1.setText(mess_str);

mBox1.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    switch ( mBox1.exec() )
    {
        case QMessageBox::Yes:
        break;

        default:
        return;
        break;
    }

close_album();

QPixmap p = create_splash_image();
QSplashScreen * splash = new QSplashScreen(p);
splash->show();
splash->showMessage( tr("Deleting all rows") );
qApp->processEvents();

QString s = QLatin1String("delete from ");
s.append(album);

QSqlQuery query(s, db);

    if ( true == query.lastError().isValid() )
    {
    QMessageBox::warning( this,
                          QLatin1String("Query Error Message (delete all)"),
                          query.lastError().text() );
    }

query.clear();

set_album( album,
           album_num,
           album_name );

splash->close();
delete splash;
}

void MainWindow::show_creds()
{
QSplashScreen * splash = new QSplashScreen( QPixmap(":/binary/about.png") );
splash->setAttribute(Qt::WA_DeleteOnClose);
splash->setWindowModality(Qt::ApplicationModal);
splash->show();

QTimer::singleShot( 30000, splash, SLOT( close() ) );
}

void MainWindow::show_manual()
{
ManualWidget * manualwidget = new ManualWidget(lang);
manualwidget->setAttribute(Qt::WA_DeleteOnClose);
manualwidget->show();
}

void MainWindow::conf_view()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

bool filter_set = false;
    if ( true == setFilterButton->isChecked() )
    {
    filter_set = true;
        if ( true == filter_.isEmpty() )
        {
        filter_set = false;
        }
    }

QMap<QString, QString> m;
SelectCollectionDialog1 * sd = new SelectCollectionDialog1;
sd->show();
    if (sd->exec() != QDialog::Accepted)
    {
    sd->close();
    delete sd;
    return;
    }
    else
    {
    m = sd->return_selected();
    sd->close();
    delete sd;
    }

QString table;
QString num;
QString name;
QString filter = QLatin1String("");

    if ( m.value("use_current") == QLatin1String("TRUE") )
    {
    table = opened_album;
    num = opened_album_num;
    name = opened_album_name;
    }
    else
    {
        if ( true == m.value("table").isEmpty() )
        {
        return;
        }
    table = m.value("table");
    num = m.value("num");
    name = m.value("name");
    }

table = table.toUpper();

read_indicies(table);

SetViewDialog * d = new SetViewDialog( table,
                                       num,
                                       name,
                                       asc_index_columns,
                                       desc_index_columns );
int default_view = 0;
    if ( d->exec() != QDialog::Accepted )
    {
    d->close();
    delete d;
    return;
    }
    else
    {
    default_view = d->return_selection();
    d->close();
    delete d;
    }

close_album();
    if ( default_view == 1 )
    {
    set_default_view(table);
    }
set_album( table, num, name );
}

void MainWindow::set_album_view( QString album )
{
columns_show.clear();
column_width.clear();

QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

QString s =
QLatin1String("select column_id,show_hide,width from ");
s.append(album);
s.append( QLatin1String("_options") );
QSqlQuery query(s, db);
    while (query.next())
    {
    int column_id = query.value(0).toInt();
    int show = query.value(1).toInt();
    int width = query.value(2).toInt();
        if ( show == 1 )
        {
        columns_show[column_id] = 1;
        }
        else
        {
        columns_show[column_id] = 0;
        }

        if ( width >= 41 && width <= 900 )
        {
        column_width[column_id] = width;
        }
        else
        {
        column_width[column_id] = 40;
        }
    }
query.clear();
}

void MainWindow::close_db()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
close_album();
set_empty_view();
db.close();
db_opened = false;
}

void MainWindow::set_default_view( QString album )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

    if ( true == album.isEmpty() )
    {
    return;
    }

Schema * schema = new Schema;
    if ( NULL == schema )
    {
    return;
    }
QList<int> default_view = schema->default_view();
int columns_count = schema->columns_count();

    for ( int i = 1; i < columns_count; i++ )
    {
    QString s = QLatin1String("update ");
    s.append(album);
    s.append( QLatin1String("_options set ") );
    s.append( QLatin1String("show_hide = ") );

        if ( true == default_view.contains(i) )
        {
        s.append( QLatin1String("1") );
        }
        else
        {
        s.append( QLatin1String("0") );
        }
    s.append( QLatin1String(" where column_id = ") );
    s.append( QString::number(i) );
    QSqlQuery query(s, db);
        if ( true == query.lastError().isValid() )
        {
        QMessageBox::warning( this,
                              QLatin1String("Query Error Message (show/hide)"),
                              query.lastError().text() );
        }
    query.clear();
    }

QString str = QLatin1String("update ");
str.append(album);
str.append( QLatin1String("_options set width = 100") );
QSqlQuery query_width(str, db);
    if ( true == query_width.lastError().isValid() )
    {
    QMessageBox::warning( this,
                          QLatin1String("Query Error Message (width)"),
                          query_width.lastError().text() );
    }
query_width.clear();

}

void MainWindow::writeSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);
settings.beginGroup( QLatin1String("MainWindow") );
settings.setValue( QLatin1String("size"), QVariant( this->size() ) );
settings.setValue( QLatin1String("pos"), QVariant( this->pos() ) );
settings.endGroup();
}

void MainWindow::readSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);
settings.beginGroup( QLatin1String("MainWindow") );
resize( settings.value( QLatin1String("size"), QSize( 930, 620 ) ).toSize() );
move( settings.value( QLatin1String("pos"), QPoint( 0, 0 ) ).toPoint() );
settings.endGroup();
}

void MainWindow::check_ru()
{
actionRussian->setChecked(true);
switch_to_ru(true);
}

void MainWindow::check_de()
{
actionGerman->setChecked(true);
switch_to_de(true);
}

void MainWindow::check_en()
{
actionEnglish->setChecked(true);
}

/*
void MainWindow::check_zh_CN()
{
actionZh->setChecked(true);
switch_to_zh_CN(true);
}
*/

void MainWindow::set_default_font()
{
QFont f;
bool ok = false;
ok = f.fromString(default_font_str);
        if ( true == ok )
        {
        QApplication::setFont(f);
        }
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);
settings.beginGroup( QLatin1String("GlobalSettings") );
settings.remove( QLatin1String("font") );
settings.endGroup();
}

void MainWindow::show_chars()
{
CharsWidget * w = new CharsWidget();
w->set_model();
w->show();
}

void MainWindow::export_xml()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

bool filter_set = false;
    if ( true == setFilterButton->isChecked() )
    {
    filter_set = true;
        if ( true == filter_.isEmpty() )
        {
        filter_set = false;
        }
    }

QMap<QString, QString> m;
SelectCollectionDialog * d = new SelectCollectionDialog( collection_attrs.value("statuses"),
                                                         filter_set );
d->show();
    if (d->exec() != QDialog::Accepted)
    {
    d->close();
    delete d;
    return;
    }
    else
    {
    m = d->return_selected();
    d->close();
    delete d;
    }

QString table;
QString num;
QString name;
QString filter = QLatin1String("");

    if ( m.value("use_current") == QLatin1String("TRUE") )
    {
    table = opened_album;
    num = opened_album_num;
    name = opened_album_name;
    }
    else
    {
        if ( true == m.value("table").isEmpty() )
        {
        return;
        }
    table = m.value("table");
    num = m.value("num");
    name = m.value("name");
    }

    if ( m.value("items") == QLatin1String("ALL") )
    {
    }
    else if ( m.value("items") == QLatin1String("FILTER") )
    {
    filter = filter_;
    }
    else if ( m.value("items") == QLatin1String("STATUS") )
    {
        if ( true == m.value("status").isEmpty() )
        {
        return;
        }
        else
        {
        filter = QLatin1String(" status = ");
        filter.append( QString(QChar(0x27)) );
        filter.append( m.value("status") );
        filter.append( QString(QChar(0x27)) );
        }
    }
    else
    {
    }

QMap<QString, QVariant> sd_m;
QString path = QLatin1String("");
SaveXMLDialog * sd = new SaveXMLDialog();
QString file_name = opened_album;
file_name.append( QLatin1String(".xml") );
sd->set_file_name(file_name);
sd->show();
    if (sd->exec() != QDialog::Accepted)
    {
    sd->close();
    delete sd;
    return;
    }
    else
    {
    sd_m = sd->return_data();
    sd->close();
    delete sd;
    }

path = sd_m.value("file").toString();

    if ( true == path.isEmpty() )
    {
    QMessageBox::critical(this,
                         tr("Error"),
                         tr("Path invalid.") );
    return;
    }

QFile file_(path);
    if ( file_.exists() )
    {
    QMessageBox mBox;
    mBox.setWindowTitle( tr("File exists") );
    mBox.setIcon( QMessageBox::Question );
    mBox.setText( tr("Overwrite?") );
    mBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No );
        switch ( mBox.exec() )
        {
            case QMessageBox::Yes:
            break;

            default:
            return;
            break;
        }
    file_.open(QIODevice::WriteOnly);
    file_.remove();
    }
QFile file(path);
bool opened = file.open(QIODevice::ReadWrite | QIODevice::Append );
    if ( true != opened )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Could not open file.") );
    return;
    }

Schema * schema = new Schema();
    if ( NULL == schema )
    {
    return;
    }
QMap<int, QString> columns_headers = schema->headers();
QList<int> integers = schema->integers();
QList<int> doubles = schema->doubles();
QList<int> longlongs = schema->longlongs();
int columns_count = schema->columns_count();
int all_columns = columns_count + 5;

QPixmap p = create_splash_image();
QSplashScreen * splash = new QSplashScreen(p);
splash->show();
splash->showMessage( tr("Writing MS XML Spreadsheet File") );
qApp->processEvents();

QString header_data = QLatin1String("<?xml version=\"1.0\"?>\n");
header_data.append( QLatin1String("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n") );
header_data.append( QLatin1String("xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n") );
header_data.append( QLatin1String("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\n") );
header_data.append( QLatin1String("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\n") );
header_data.append( QLatin1String("xmlns:html=\"http://www.w3.org/TR/REC-html40\"\n") );
header_data.append( QLatin1String("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n") );
header_data.append( QLatin1String("xmlns:x2=\"http://schemas.microsoft.com/office/excel/2003/xml\">\n") );
header_data.append( QLatin1String("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\n") );
header_data.append( QLatin1String("</DocumentProperties>\n") );
header_data.append( QLatin1String("<OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">\n") );
header_data.append( QLatin1String("</OfficeDocumentSettings>\n") );
header_data.append( QLatin1String("<ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\n") );
header_data.append( QLatin1String("<ProtectStructure>False</ProtectStructure>\n") );
header_data.append( QLatin1String("<ProtectWindows>False</ProtectWindows>\n") );
header_data.append( QLatin1String("</ExcelWorkbook>\n") );
header_data.append( QLatin1String("<Styles>\n") );
header_data.append( QLatin1String("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\n") );
header_data.append( QLatin1String("<Alignment ss:Vertical=\"Bottom\"/>\n") );
header_data.append( QLatin1String("<Borders/>\n") );
header_data.append( QLatin1String("<Font/>\n") );
header_data.append( QLatin1String("<Interior/>\n") );
header_data.append( QLatin1String("<NumberFormat/>\n") );
header_data.append( QLatin1String("<Protection/>\n") );
header_data.append( QLatin1String("</Style>\n") );
header_data.append( QLatin1String("<Style ss:ID=\"s21\">\n") );
header_data.append( QLatin1String("<Font ss:Color=\"#FFFFFF\"/>\n") );
header_data.append( QLatin1String("<Interior ss:Color=\"#333399\" ss:Pattern=\"Solid\"/>\n") );
header_data.append( QLatin1String("</Style>\n") );
header_data.append( QLatin1String("</Styles>\n") );
header_data.append( QLatin1String("<Worksheet ss:Name=\"") );
header_data.append(table);
header_data.append( QLatin1String("\">\n") );
header_data.append( QLatin1String("<Table>\n") );
header_data.append( QLatin1String("<Column ss:Index=\"1\" ss:Width=\"80\"/>\n") );
header_data.append( QLatin1String("<Column ss:Index=\"") );
header_data.append( QString::number(columns_count) );
header_data.append( QLatin1String("\" ss:Width=\"80\"/>\n") );

    if ( sd_m.value("desc").toString() == QLatin1String("Y") )
    {
    header_data.append( QLatin1String("<Column ss:Index=\"") );
    header_data.append( QString::number(all_columns) );
    header_data.append( QLatin1String("\" ss:Width=\"400\"/>\n") );
    }

header_data.append( QLatin1String("<Row>\n") );

    for ( int y = 0; y < columns_headers.size(); ++y )
    {
    header_data.append( QLatin1String("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">") );
    header_data.append( columns_headers.value(y) );
    header_data.append( QLatin1String("</Data></Cell>\n") );
    }

header_data.append( QLatin1String("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">") );
header_data.append( tr("Catalogs") );
header_data.append( QLatin1String("</Data></Cell>\n") );

header_data.append( QLatin1String("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">") );
header_data.append( tr("Auctions") );
header_data.append( QLatin1String("</Data></Cell>\n") );

header_data.append( QLatin1String("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">") );
header_data.append( tr("Spots") );
header_data.append( QLatin1String("</Data></Cell>\n") );

header_data.append( QLatin1String("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">") );
header_data.append( tr("Others") );
header_data.append( QLatin1String("</Data></Cell>\n") );

    if ( sd_m.value("desc").toString() == QLatin1String("Y") )
    {
    header_data.append( QLatin1String("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">") );
    header_data.append( tr("Description") );
    header_data.append( QLatin1String("</Data></Cell>\n") );
    }

header_data.append( QLatin1String("</Row>\n") );
header_data.append( QLatin1String("\n") );

QByteArray header_ba = header_data.toUtf8();
qint64 bytes = Q_INT64_C(-1);
bytes = file.write(header_ba);

QString s = QLatin1String("select ");
s.append( schema->columns_for_query() );
s.append( QLatin1String(" from ") );
s.append(table);
    if ( true != filter.isEmpty() )
    {
    s.append(QLatin1String(" where ") );
    s.append(filter);
    }

QSqlQuery query(s, db);
    while ( query.next() )
    {
    QString row_data = QLatin1String("<Row>");
    QString desc = QLatin1String("");
    int z = 0;
    int column_ind = 0;
    z = schema->columns_count();
    int last_column = z + 5;
    qint64 coin_id = query.value(0).toLongLong();
        for ( int x = 0; x < z; ++x )
        {
        column_ind = x + 1;
        QVariant v = query.value(x);

            if ( true != v.isNull() &&
                 true == v.isValid() )
            {
            row_data.append( QLatin1String("<Cell ss:StyleID=\"Default\" ss:Index=\"") );
            row_data.append( QString::number(column_ind) );
            row_data.append( QLatin1String("\">") );

                if ( true == integers.contains(x) )
                {
                row_data.append( QLatin1String("<Data ss:Type=\"Number\">") );
                row_data.append( QString::number( v.toInt() ) );
                row_data.append( QLatin1String("</Data>") );
                }
                else if ( true == doubles.contains(x) )
                {
                row_data.append( QLatin1String("<Data ss:Type=\"Number\">") );
                row_data.append( QString::number( v.toDouble() ) );
                row_data.append( QLatin1String("</Data>") );
                }
                else if ( true == longlongs.contains(x) )
                {
                row_data.append( QLatin1String("<Data ss:Type=\"Number\">") );
                row_data.append( QString::number( v.toLongLong() ) );
                row_data.append( QLatin1String("</Data>") );
                }
                else
                {
                row_data.append( QLatin1String("<Data ss:Type=\"String\">") );
                row_data.append( v.toString() );
                row_data.append( QLatin1String("</Data>") );
                }
            row_data.append( QLatin1String("</Cell>\n") );
            }
        }
    
    // Catalogs
    column_ind += 1;
    
    QStringList cats_list;
    QString s3 = QLatin1String("select cat_name,int_id,cat_note,cat_pr_f,cat_pr_vf,cat_pr_xf,cat_pr_unc,cat_curr from ");
    s3.append(table);
    s3.append( QLatin1String("_catalogs where coin_id = ") );
    s3.append( QString::number(coin_id) );
    QSqlQuery query3(s3, db);
        while ( query3.next() )
        {
        QString cats_query_s = QLatin1String("");
        cats_query_s.append(query3.value(0).toString());
        cats_query_s.append( QLatin1String(" "));
        cats_query_s.append(query3.value(1).toString());
        cats_query_s.append( QLatin1String(" "));
        cats_query_s.append(query3.value(2).toString());
        cats_query_s.append( QLatin1String(" "));
        cats_query_s.append(QString::number(query3.value(3).toDouble()));
        cats_query_s.append( QLatin1String(" "));
        cats_query_s.append(QString::number(query3.value(4).toDouble()));
        cats_query_s.append( QLatin1String(" "));
        cats_query_s.append(QString::number(query3.value(5).toDouble()));
        cats_query_s.append( QLatin1String(" "));
        cats_query_s.append(QString::number(query3.value(6).toDouble()));
        cats_query_s.append( QLatin1String(" "));
        cats_query_s.append(query3.value(7).toString());
        
        cats_list << cats_query_s;
        }
    query3.clear();
        if ( true != cats_list.isEmpty() )
        {
        QString cats_s = QLatin1String("");
            for (int j = 0; j < cats_list.size(); j++)
            {
            cats_s.append(cats_list.at(j));
            cats_s.append(QLatin1String("\n"));
            }	
            if ( true != cats_s.isEmpty() )
            {
            row_data.append( QLatin1String("<Cell ss:StyleID=\"Default\" ss:Index=\"") );
            row_data.append( QString::number(column_ind) );
            row_data.append( QLatin1String("\">") );
            row_data.append( QLatin1String("<Data ss:Type=\"String\">") );
            row_data.append(cats_s);
            row_data.append( QLatin1String("</Data>") );
            row_data.append( QLatin1String("</Cell>\n") );
            }
        } 

    // Auctions
    column_ind += 1;
    
    QStringList aucts_list;
    QString s4 = QLatin1String("select auct_name,auct_date,auct_note,auct_cond,auct_pr,auct_curr from ");
    s4.append(table);
    s4.append( QLatin1String("_auctions where coin_id = ") );
    s4.append( QString::number(coin_id) );
    QSqlQuery query4(s4, db);
        while ( query4.next() )
        {
        QString auct_query_s = QLatin1String("");
        auct_query_s.append(query4.value(0).toString());
        auct_query_s.append( QLatin1String(" "));
        auct_query_s.append(QString::number(query4.value(1).toInt()));
        auct_query_s.append( QLatin1String(" "));
        auct_query_s.append(query4.value(2).toString());
        auct_query_s.append( QLatin1String(" "));
        auct_query_s.append(query4.value(3).toString());
        auct_query_s.append( QLatin1String(" "));
        auct_query_s.append(QString::number(query4.value(4).toDouble()));
        auct_query_s.append( QLatin1String(" "));
        auct_query_s.append(query4.value(5).toString());
        
        aucts_list << auct_query_s;
        }
    query4.clear();
        if ( true != aucts_list.isEmpty() )
        {
        QString aucts_s = QLatin1String("");
            for (int j = 0; j < aucts_list.size(); j++)
            {
            aucts_s.append(aucts_list.at(j));
            aucts_s.append(QLatin1String("\n"));
            }
            if ( true != aucts_s.isEmpty() )
            {
            row_data.append( QLatin1String("<Cell ss:StyleID=\"Default\" ss:Index=\"") );
            row_data.append( QString::number(column_ind) );
            row_data.append( QLatin1String("\">") );
            row_data.append( QLatin1String("<Data ss:Type=\"String\">") );
            row_data.append(aucts_s);
            row_data.append( QLatin1String("</Data>") );
            row_data.append( QLatin1String("</Cell>\n") );
            }
        } 

    // Spots
    column_ind += 1;
    
    QStringList spots_list;
    QString s5 = QLatin1String("select spot_name,note,coord,latitude,longitude,spot_date from ");
    s5.append(table);
    s5.append( QLatin1String("_spots where coin_id = ") );
    s5.append( QString::number(coin_id) );
    QSqlQuery query5(s5, db);
        while ( query5.next() )
        {
        QString spots_query_s = QLatin1String("");
        spots_query_s.append(query5.value(0).toString());
        spots_query_s.append( QLatin1String(" "));
        spots_query_s.append(query5.value(1).toString());
        spots_query_s.append( QLatin1String(" "));
        spots_query_s.append(query5.value(2).toString());
        spots_query_s.append( QLatin1String(" "));
        spots_query_s.append(QString::number(query5.value(3).toDouble()));
        spots_query_s.append( QLatin1String(" "));
        spots_query_s.append(QString::number(query5.value(4).toDouble()));
        spots_query_s.append( QLatin1String(" "));
        spots_query_s.append(QString::number(query5.value(4).toInt()));
        
        spots_list << spots_query_s;
        }
    query5.clear();
        if ( true != spots_list.isEmpty() )
        {
        QString spots_s = QLatin1String("");
            for (int j = 0; j < spots_list.size(); j++)
            {
            spots_s.append(spots_list.at(j));
            spots_s.append(QLatin1String("\n"));
            }
            if ( true != spots_s.isEmpty() )
            {
            row_data.append( QLatin1String("<Cell ss:StyleID=\"Default\" ss:Index=\"") );
            row_data.append( QString::number(column_ind) );
            row_data.append( QLatin1String("\">") );
            row_data.append( QLatin1String("<Data ss:Type=\"String\">") );
            row_data.append(spots_s);
            row_data.append( QLatin1String("</Data>") );
            row_data.append( QLatin1String("</Cell>\n") );
            }
        } 

    // Other
    column_ind += 1;
    
    QStringList others_list;
    QString s6 = QLatin1String("select name,text_1,text_2,other_date from ");
    s6.append(table);
    s6.append( QLatin1String("_other where coin_id = ") );
    s6.append( QString::number(coin_id) );
    QSqlQuery query6(s6, db);
        while ( query6.next() )
        {
        QString others_query_s = QLatin1String("");
        others_query_s.append(query6.value(0).toString());
        others_query_s.append( QLatin1String(" "));
        others_query_s.append(query6.value(1).toString());
        others_query_s.append( QLatin1String(" "));
        others_query_s.append(query6.value(2).toString());
        others_query_s.append( QLatin1String(" "));
        others_query_s.append(QString::number(query6.value(3).toInt()));

        others_list << others_query_s;
        }
    query6.clear();
        if ( true != others_list.isEmpty() )
        {
        QString others_s = QLatin1String("");
            for (int j = 0; j < others_list.size(); j++)
            {
            others_s.append(others_list.at(j));
            others_s.append(QLatin1String("\n"));
            }
            if ( true != others_s.isEmpty() )
            {
            row_data.append( QLatin1String("<Cell ss:StyleID=\"Default\" ss:Index=\"") );
            row_data.append( QString::number(column_ind) );
            row_data.append( QLatin1String("\">") );
            row_data.append( QLatin1String("<Data ss:Type=\"String\">") );
            row_data.append(others_s);
            row_data.append( QLatin1String("</Data>") );
            row_data.append( QLatin1String("</Cell>\n") );
            }
        }
    
    // descriprion (last column!)
        if ( sd_m.value("desc").toString() == QLatin1String("Y") )
        {
        QString s_desc = QLatin1String("select desc_b from ");
        s_desc.append(table);
        s_desc.append( QLatin1String("_desc_blobs where coin_id = ") );
        s_desc.append( QString::number(coin_id) );
        QSqlQuery query_desc(s_desc, db);
            while ( query_desc.next() )
            {
                if ( true != query_desc.value(0).isNull() )
                {
                QByteArray ba = query_desc.value(0).toByteArray();
                QString ts = QString::fromUtf8( ba.constData() );
                QTextDocument * doc = new QTextDocument;
                doc->setHtml(ts);
                desc = doc->toPlainText();
                    if ( sd_m.value("trunc").toString() == QLatin1String("Y") )
                    {
                        if ( sd_m.value("chars").toInt() > 0 )
                        {
                        desc.truncate( sd_m.value("chars").toInt() );
                        }
                        else
                        {
                        desc.truncate(256);
                        statusBar()->showMessage( tr("Trucate value not found, used 256.") );
                        qApp->processEvents();
                        }
                    }
                delete doc;
                }
            }
        query_desc.clear();
        }

    row_data.append( QLatin1String("<Cell ss:StyleID=\"Default\" ss:Index=\"") );
    row_data.append( QString::number(last_column) );
    row_data.append( QLatin1String("\">") );
        if ( sd_m.value("desc").toString() == QLatin1String("Y") )
        {
            if ( true != desc.isEmpty() )
            {
            row_data.append( QLatin1String("<Data ss:Type=\"String\">") );
            row_data.append(desc);
            row_data.append( QLatin1String("</Data>") );
            }
        }
    row_data.append( QLatin1String("</Cell>\n") );

    row_data.append( QLatin1String("</Row>\n") );
    QByteArray row_ba = row_data.toUtf8();
    bytes += file.write(row_ba);
    }
query.clear();

QString end_data = QLatin1String("</Table>");
end_data.append( QLatin1String("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">") );
end_data.append( QLatin1String("<Selected/>\n") );
end_data.append( QLatin1String("<ProtectObjects>False</ProtectObjects>\n") );
end_data.append( QLatin1String("<ProtectScenarios>False</ProtectScenarios>\n") );
end_data.append( QLatin1String("</WorksheetOptions>\n") );
end_data.append( QLatin1String("<x:WorksheetOptions/>\n") );
end_data.append( QLatin1String("</Worksheet>\n") );
end_data.append( QLatin1String("</Workbook>\n") );

QByteArray end_ba = end_data.toUtf8();
bytes += file.write(end_ba);

bool success = false;
success = file.flush();
file.close();

delete schema;
QString message = tr("Wrote");
message.append( QLatin1String(" ") );
message.append( QString::number(bytes) );
message.append( QLatin1String(" ") );
message.append( tr("bytes") );
statusBar()->showMessage(message, 5000);
qApp->processEvents();
splash->close();
delete splash;

    if ( true != success )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Could not save file.") );
    return;
    }

}

void MainWindow::update_edit_button()
{
textChangedLabel->setMovie(m0);
m0->start();
saveTextLabel->setMovie(m1);
m1->start();
}

void MainWindow::preview_html()
{
PreviewHTMLWidget * w = new PreviewHTMLWidget();
w->show();
descTextEdit->setAcceptRichText(false);
QString t = descTextEdit->toPlainText();
w->set_text(t);
}

QString MainWindow::process_value( int i, QVariant v, bool append_comma )
{
QString r = QLatin1String("");

Schema * schema = new Schema;
    if ( schema == NULL )
    {
    return r;
    }
QList<int> doubles = schema->doubles();
QList<int> integers = schema->integers();
QList<int> longlongs = schema->longlongs();
QList<int> integer_dates = schema->integer_dates();
QList<int> bools = schema->bools();

    if ( true != v.isNull() &&
         true == v.isValid() )
    {
        if ( true == integers.contains(i) )
        {
        int x;
        bool ok = false;
        x = v.toInt(&ok);
            if ( true == ok )
            {
            r = QString::number( x );
            }
            else
            {
            r = QLatin1String("null");
            }
        }
        else if ( true == integer_dates.contains(i) )
        {
        int x;
        bool ok = false;
        x = v.toInt(&ok);
            if ( true == ok )
            {
            r = QString::number( x );
            }
            else
            {
            r = QLatin1String("null");
            }
        }
        else if ( doubles.contains(i) )
        {
        double y;
        bool ok = false;
        y = v.toDouble(&ok);
            if ( true == ok )
            {
            r = QString::number( y );
            }
            else
            {
            r = QLatin1String("null");
            }
        }
        else if ( longlongs.contains(i) )
        {
        qint64 ll = Q_INT64_C(-1);
        bool ok = false;
        ll = v.toLongLong(&ok);
            if ( true == ok )
            {
            r = QString::number( ll );
            }
            else
            {
            r = QLatin1String("null");
            }
        }
        else if ( true == bools.contains(i) )
        {
        QString raw_str = v.toString();
            if ( raw_str == QLatin1String("Y") ||
                 raw_str == QLatin1String("y") ||
                 raw_str == QLatin1String("1") ||
                 raw_str == QLatin1String("true") ||
                 raw_str == QLatin1String("True") ||
                 raw_str == QLatin1String("TRUE") )
            {
            QString str = QString(QChar(0x27));
            str.append( QLatin1String("Y") );
            str.append( QString(QChar(0x27)) );
            r = str;
            }
            else
            {
            r = QLatin1String("null");
            }
        }        
        else
        {
        QString s = v.toString();
            if ( true != s.isEmpty() )
            {
                if (s.contains(QChar(0x27)))
                {
                QString ns = QString("");
                    for (int x = 0; x < s.length(); x++)
                    {
                    QChar c(s.at(x));
                        if (c == QChar(0x27))
                        {
                        ns.append(c);
                        ns.append(c);
                        }
                        else
                        {
                        ns.append(c);
                        }
                    }
                r.append(QChar(0x27));
                r.append(ns);
                r.append(QChar(0x27));
                }
                else
                {
                r.append(QChar(0x27));
                r.append( s );
                r.append(QChar(0x27));
                }
            }
            else
            {
            r = QLatin1String("null");
            }
        }
    }
    else
    {
    r = QLatin1String("null");
    }

    if ( true == append_comma )
    {
    r.append( QLatin1String(",") );
    }

delete schema;
return r;
}

QString MainWindow::preprocess_varchar( QString s, int x )
{
QString r;
Schema * schema = new Schema;
    if ( NULL == schema )
    {
    return r;
    }
int l = schema->varchar_size(x);
    if ( true != s.isEmpty() )
    {
        if ( l > 0 )
        {
        s.truncate(l);
        }
    r = QString(QChar(0x27));
        if (s.contains(QChar(0x27)))
        {
        QString ns = QString("");
            for (int x = 0; x < s.length(); x++)
            {
            QChar c(s.at(x));
                if (c == QChar(0x27))
                {
                ns.append(c);
                ns.append(c);
                }
                else
                {
                ns.append(c);
                }
            }
        r.append(ns);
        }
        else
        {
        r.append(s);
        }
    r.append( QString(QChar(0x27)) );
    }
    else
    {
    r = QLatin1String("null");
    }
return r;
}

bool MainWindow::test_files( QString file1, QString file2 )
{
QFileInfo fi1(file1);
QFileInfo fi2(file2);
    if ( fi1.absoluteFilePath() == fi2.absoluteFilePath() )
    {
    return false;
    }
return true;
}

QString MainWindow::preprocess_fast_update( QMap<QString, QVariant> m )
{
QString s = QLatin1String("");

Schema * schema = new Schema();
    if ( NULL == schema )
    {
    return s;
    }
QMap<int, QString> headers = schema->headers();
QList<int> doubles = schema->doubles();
QList<int> integers = schema->integers();
QList<int> bools = schema->bools();
QList<int> longlongs = schema->longlongs();
QList<int> strings = schema->strings();
QList<int> integer_dates = schema->integer_dates();

QString raw_str = QLatin1String("");

int j = -1;
    if ( m.value("index").toInt() >= 0 )
    {
    j = m.value("index").toInt() + 1;
    }
    else
    {
    delete schema;
    return s;
    }

    if ( headers.value(j) != m.value("name").toString() )
    {
    delete schema;
    return s;
    }
    else
    {
    raw_str = m.value("value").toString();
    }

    if ( true == integer_dates.contains(j) )
    {
    QDate date = QDate::fromString(raw_str, "yyyyMMdd");
        if ( true == date.isValid() )
        {
        s = raw_str;
        }
    }
    else if ( true == integers.contains(j) )
    {
    QRegExp rx("\\D");
    bool match = raw_str.contains(rx);
        if ( true != match)
        {
        bool ok = false;
        int num = raw_str.toInt( &ok, 10);
            if ( true == ok )
            {
            s = QString::number(num);
            }
        }
    }
    else if ( true == doubles.contains(j) )
    {
    bool ok = false;
    double num = raw_str.toDouble(&ok);
        if ( true == ok )
        {
        s = QString::number(num);
        }
    }
    else if ( true == longlongs.contains(j) )
    {
    bool ok = false;
    int num = raw_str.toLongLong(&ok);
        if ( true == ok )
        {
        s = QString::number(num);
        }
    }
    else if ( true == bools.contains(j) )
    {
        if ( raw_str == QLatin1String("Y") ||
             raw_str == QLatin1String("y") ||
             raw_str == QLatin1String("1") ||
             raw_str == QLatin1String("true") ||
             raw_str == QLatin1String("True") ||
             raw_str == QLatin1String("TRUE") )
        {
        QString str = QString(QChar(0x27));
        str.append( QLatin1String("Y") );
        str.append( QString(QChar(0x27)) );
        s = str;
        }
    }
    else
    {
    s = preprocess_varchar( raw_str, j );
    }

delete schema;
return s;
}

void MainWindow::fast_update()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

TabModel1 * model = qobject_cast<TabModel1 *>( tableView->model() );
    if ( NULL == model )
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = tableView->selectionModel();
    if ( NULL == selectionModel )
    {
    return;
    }

QModelIndexList currentSelection = selectionModel->selectedRows(0);
    if ( currentSelection.isEmpty() )
    {
    QMessageBox::information( this,
                              tr("Information"),
                              tr("Nothing is selected.") );
    return;
    }

Schema * schema = new Schema();
    if ( NULL == schema )
    {
    return;
    }
QMap<int, QString> column_names = schema->column_names();

QString table = opened_album;
QString table_num = opened_album_num;
QString table_name = opened_album_name;

QStringList ids_list;

QSplashScreen * splash1 = new QSplashScreen( create_splash_image() );
    if ( currentSelection.size() >= 100 )
    {
    splash1->show();
    splash1->showMessage( tr("Processing Items") );
    qApp->processEvents();
    }

    for ( int i = 0; i < currentSelection.size(); ++i )
    {
    ids_list << QString::number( model->record( currentSelection.at(i).row() ).value("ID").toLongLong() );
    }

    if ( currentSelection.size() >= 100 )
    {
    splash1->close();
    }
delete splash1;

QMap<QString, QVariant> m;
UpdateValuesDialog * d = new UpdateValuesDialog( collection_attrs );
d->show();
    if (d->exec() != QDialog::Accepted)
    {
    d->close();
    delete schema;
    delete d;
    return;
    }
    else
    {
    m = d->return_selection();
    d->close();
    delete schema;
    delete d;
    }

QString column_str = QLatin1String("");
QString value_str = QLatin1String("");

    if ( QString( QLatin1String("Y") ) == m.value("is_null").toString() )
    {
    value_str = QLatin1String("null");
    }
    else
    {
    value_str = preprocess_fast_update(m);
    }


    if (  true == value_str.isEmpty() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Invalid value.") );
    return;
    }
int j = m.value("index").toInt() + 1;
column_str = column_names.value(j);

close_album();

ProgressDialog * pw = new ProgressDialog( ids_list.size() );
pw->show();

blocking = 1;

int count = 0;
   for ( int x = 0; x < ids_list.size(); x += 512 )
   {
   QStringList tl;
       for ( int y = x; y <= x + 511; y += 1 )
       {
           if ( y >= ids_list.size() )
           {
           break;
           }
       count += 1;
       QString mes_s = tr("Updating ID");
       mes_s.append( QLatin1String(" ") );
       mes_s.append( ids_list.at(y) );
       tl << ids_list.at(y);
       statusBar()->showMessage(mes_s, 2000);
       pw->set_value(count);
       qApp->processEvents();
       }

   QString s = QLatin1String("update ");
   s.append(table);
   s.append( QLatin1String(" set ") );
   s.append(column_str);
   s.append( QLatin1String(" = ") );
   s.append(value_str);
   s.append( QLatin1String(" where id in (") );
   s.append( tl.join(",") );
   s.append( QLatin1String(")") );
   QSqlQuery query(s, db);
       if ( true == query.lastError().isValid() )
       {
       QMessageBox::critical( this,
                              QLatin1String("Query Error Message (update status)"),
                              query.lastError().text() );
       }
   query.clear();
   }

blocking = 0;

qApp->processEvents();
pw->close();
delete pw;

set_album( table,
           table_num,
           table_name );

}

void MainWindow::print_item()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

TabModel1 * model = qobject_cast<TabModel1 *>(tableView->model());
    if (NULL == model)
    {
    set_empty_view();
    return;
    }

QItemSelectionModel * selectionModel = tableView->selectionModel();
    if (NULL == selectionModel)
    {
    return;
    }
QModelIndexList currentSelection = selectionModel->selectedRows(0);

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Information"),
                              tr("Nothing is selected.") );
    return;
    }

QMap<QString, QString> m;
PrintDocDialog * pd = new PrintDocDialog;
pd->show();
    if ( pd->exec() != QDialog::Accepted )
    {
    pd->close();
    delete pd;
    return;
    }
    else
    {
    m = pd->return_data();
    pd->close();
    delete pd;
    }

qApp->processEvents();
QSplashScreen * splash = new QSplashScreen( create_splash_image() );
splash->show();
splash->showMessage("Creating Document ...");
qApp->processEvents();

QSqlRecord record = QSqlRecord( model->record( currentSelection.at(0).row() ) );

CreateDoc * cd = new CreateDoc();
cd->create_doc( m, opened_album, record );
QTextDocument * d = cd->return_doc();
PrintView * w = new PrintView;
w->set_doc(d);
w->show();
splash->finish(w);
delete splash;
}

void MainWindow::print_file()
{
QTextDocument * document = descTextEdit->document();
QPrinter printer;
QPrintDialog * dialog = new QPrintDialog( &printer, this );
dialog->setWindowTitle( tr("Print Description") );
    if ( dialog->exec() != QDialog::Accepted )
    {
    return;
    }
document->print( &printer );
}

void MainWindow::show_value()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

bool filter_set = false;
    if ( true == setFilterButton->isChecked() )
    {
    filter_set = true;
        if ( true == filter_.isEmpty() )
        {
        filter_set = false;
        }
    }

QMap<QString, QString> m;
SelectCollectionDialog * d = new SelectCollectionDialog( collection_attrs.value("statuses"),
                                                         filter_set );
d->show();
    if (d->exec() != QDialog::Accepted)
    {
    d->close();
    delete d;
    return;
    }
    else
    {
    m = d->return_selected();
    d->close();
    delete d;
    }

QString table;
QString num;
QString name;
QString filter = QLatin1String("");

    if ( m.value("use_current") == QLatin1String("TRUE") )
    {
    table = opened_album;
    num = opened_album_num;
    name = opened_album_name;
    }
    else
    {
        if ( true == m.value("table").isEmpty() )
        {
        return;
        }
    table = m.value("table");
    num = m.value("num");
    name = m.value("name");
    }

    if ( m.value("items") == QLatin1String("ALL") )
    {
    }
    else if ( m.value("items") == QLatin1String("FILTER") )
    {
    filter = filter_;
    }
    else if ( m.value("items") == QLatin1String("STATUS") )
    {
        if ( true == m.value("status").isEmpty() )
        {
        return;
        }
        else
        {
        filter = QLatin1String(" status = ");
        filter.append( QString(QChar(0x27)) );
        filter.append( m.value("status") );
        filter.append( QString(QChar(0x27)) );
        }
    }
    else
    {
    }

statusBar()->showMessage( tr("Selecting data"), 2000 );
QList< QMap<QString, QString> > l;
QString s =
QLatin1String("select act_curr,sum(act_value) from ");
s.append(table);
    if ( true != filter.isEmpty() )
    {
    s.append(QLatin1String(" where ") );
    s.append(filter);
    }
s.append( QLatin1String(" group by act_curr") );
QSqlQuery query(s, db);
    while ( query.next() )
    {
        if ( query.value(1).isNull() ||
             query.value(1).toString().isEmpty() )
        {
        }
        else
        {
        QMap<QString, QString> m1;
        m1["curr"] = query.value(0).toString();
        m1["value"] = query.value(1).toString();
        l << m1;
        }
    }
query.clear();

statusBar()->showMessage( tr("Done"), 2000 );
QString title_str = QLatin1String("<b>");
title_str.append( num );
title_str.append( QLatin1String(" ") );
title_str.append( name );
title_str.append( QLatin1String("</b>") );
ValueWidget * w = new ValueWidget( l,
                                   title_str );
w->show();
}

void MainWindow::print_report()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

bool filter_set = false;
    if ( true == setFilterButton->isChecked() )
    {
    filter_set = true;
        if ( true == filter_.isEmpty() )
        {
        filter_set = false;
        }
    }

QMap<QString, QString> m;
SelectCollectionDialog * d = new SelectCollectionDialog( collection_attrs.value("statuses"),
                                                         filter_set );
d->show();
    if (d->exec() != QDialog::Accepted)
    {
    d->close();
    delete d;
    return;
    }
    else
    {
    m = d->return_selected();
    d->close();
    delete d;
    }

QString table;
QString num;
QString name;
QString filter = QLatin1String("");

    if ( m.value("use_current") == QLatin1String("TRUE") )
    {
    table = opened_album;
    num = opened_album_num;
    name = opened_album_name;
    }
    else
    {
        if ( true == m.value("table").isEmpty() )
        {
        return;
        }
    table = m.value("table");
    num = m.value("num");
    name = m.value("name");
    }

    if ( m.value("items") == QLatin1String("ALL") )
    {
    }
    else if ( m.value("items") == QLatin1String("FILTER") )
    {
    filter = filter_;
    }
    else if ( m.value("items") == QLatin1String("STATUS") )
    {
        if ( true == m.value("status").isEmpty() )
        {
        return;
        }
        else
        {
        filter = QLatin1String(" status = ");
        filter.append( QString(QChar(0x27)) );
        filter.append( m.value("status") );
        filter.append( QString(QChar(0x27)) );
        }
    }
    else
    {
    }

}

void MainWindow::print_pricelist()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

bool filter_set = false;
    if ( true == setFilterButton->isChecked() )
    {
    filter_set = true;
        if ( true == filter_.isEmpty() )
        {
        filter_set = false;
        }
    }

QMap<QString, QString> m;
SelectCollectionDialog * d = new SelectCollectionDialog( collection_attrs.value("statuses"),
                                                         filter_set );
d->show();
    if (d->exec() != QDialog::Accepted)
    {
    d->close();
    delete d;
    return;
    }
    else
    {
    m = d->return_selected();
    d->close();
    delete d;
    }

QString table;
QString num;
QString name;
QString filter = QLatin1String("");

    if ( m.value("use_current") == QLatin1String("TRUE") )
    {
    table = opened_album;
    num = opened_album_num;
    name = opened_album_name;
    }
    else
    {
        if ( true == m.value("table").isEmpty() )
        {
        return;
        }
    table = m.value("table");
    num = m.value("num");
    name = m.value("name");
    }

    if ( m.value("items") == QLatin1String("ALL") )
    {
    }
    else if ( m.value("items") == QLatin1String("FILTER") )
    {
    filter = filter_;
    }
    else if ( m.value("items") == QLatin1String("STATUS") )
    {
        if ( true == m.value("status").isEmpty() )
        {
        return;
        }
        else
        {
        filter = QLatin1String(" status = ");
        filter.append( QString(QChar(0x27)) );
        filter.append( m.value("status") );
        filter.append( QString(QChar(0x27)) );
        }
    }
    else
    {
    }

}

void MainWindow::print_pdf()
{
QSplashScreen * s = new QSplashScreen( create_splash_image() );
QString f = QFileDialog::getSaveFileName( this,
                                          tr("Create PDF File"),
                                          QString(),
                                          QLatin1String("*.pdf") );
    if ( true != f.isEmpty() )
    {
        if ( true == QFileInfo(f).suffix().isEmpty() )
        {
        f.append(".pdf");
        }
    QPrinter printer( QPrinter::HighResolution );
    printer.setOutputFormat( QPrinter::PdfFormat );
    printer.setOutputFileName(f);
        if ( NULL != descTextEdit->document() )
        {
        s->show();
        s->showMessage( tr("Creating PDF File ...") );
        qApp->processEvents();
        descTextEdit->document()->print(&printer);
        s->close();
        }
    }
delete s;
}

QPixmap MainWindow::create_splash_image()
{
QPixmap p;
bool found_in_cache = false;
found_in_cache = QPixmapCache::find( QLatin1String("splash_image"), p );
    if ( true != found_in_cache )
    {
    QString path = db_root;
    path.append ( QDir::separator() );
    path.append( QLatin1String("splash_image.png") );
    QFile f(path);
    bool ok = false;
    ok = f.open(QIODevice::ReadOnly);
        if ( true != ok )
        {
        statusBar()->showMessage( tr("File \"splash_image.png\" doesn\'t exist."), 10000 );
        qApp->processEvents();
        p = QPixmap(":/binary/empty_splash.png");
        return p;
        }
    p = QPixmap(path);
        if ( true == p.isNull() )
        {
        p = QPixmap(":/binary/empty_splash.png");
        }
    QPixmapCache::insert( QLatin1String("splash_image"), p );
    }
return p;
}

void MainWindow::read_indicies(QString table)
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

Schema * schema = new Schema();
    if ( NULL == schema )
    {
    return;
    }
QMap<QString, int> columns_map = schema->columns_map();

asc_index_columns.clear();
QString s1 = QLatin1String("select b.RDB$FIELD_NAME from RDB$INDICES a, RDB$INDEX_SEGMENTS b");
s1.append( QLatin1String(" where a.RDB$RELATION_NAME = \'") );
s1.append(table);
s1.append( QLatin1String("\' and a.RDB$INDEX_NAME = b.RDB$INDEX_NAME") );
s1.append( QLatin1String(" and a.RDB$SEGMENT_COUNT = 1") );
s1.append( QLatin1String(" and (a.RDB$INDEX_TYPE = 0 or a.RDB$INDEX_TYPE is null)") );
QSqlQuery query1(s1, db);
    while ( query1.next() )
    {
    QString col_name = query1.value(0).toString();
    col_name = col_name.trimmed();
        if ( true != col_name.isEmpty() )
        {
        int x = columns_map.value(col_name);
        asc_index_columns[x] = 1;
        }
    }
query1.clear();

desc_index_columns.clear();
QString s2 = QLatin1String("select b.RDB$FIELD_NAME from RDB$INDICES a, RDB$INDEX_SEGMENTS b");
s2.append( QLatin1String(" where a.RDB$RELATION_NAME = \'") );
s2.append(table);
s2.append( QLatin1String("\' and a.RDB$INDEX_NAME = b.RDB$INDEX_NAME") );
s2.append( QLatin1String(" and a.RDB$INDEX_TYPE = 1") );
s2.append( QLatin1String(" and a.RDB$SEGMENT_COUNT = 1") );
QSqlQuery query2(s2, db);
    while ( query2.next() )
    {
    QString col_name = query2.value(0).toString();
    col_name = col_name.trimmed();
        if ( true != col_name.isEmpty() )
        {
        int x = columns_map.value(col_name);
        desc_index_columns[x] = 1;
        }
    }
query2.clear();
}

void MainWindow::run_query()
{
QueryWidget * w = new QueryWidget(opened_album, number_of_collections, last_exp_save_dir);
w->show();
}

void MainWindow::browse_db()
{
QMap<QString, QVariant> m;
ConnectionDialog * d = new ConnectionDialog;
d->show();
    if (d->exec() != QDialog::Accepted)
    {
    d->close();
    delete d;
    d = NULL;
    return;
    }
    else
    {
    m = d->return_config();
    d->close();
    delete d;
    d = NULL;
    }

BrowserWidget * bw = new BrowserWidget(m);
qApp->processEvents();
bw->show();
}

void MainWindow::export_sqlite()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    close_db();
    return;
    }

    if ( true == opened_album.isEmpty() )
    {
    return;
    }

Schema * schema = new Schema();
    if ( NULL == schema )
    {
    return;
    }

QMap<QString, QVariant> m;

SqliteExpDialog * d = new SqliteExpDialog();
d->show();
    if (d->exec() != QDialog::Accepted)
    {
    delete schema;
    d->close();
    delete d;
    d = NULL;
    return;
    }
    else
    {
    m = d->return_data();
    d->close();
    delete d;
    d = NULL;
    }

QString path = m.value("file").toString();

    if ( true == path.isEmpty() )
    {
    QMessageBox::critical(this,
                         tr("Error"),
                         tr("Path invalid.") );
    delete schema;
    return;
    }

QFile file(path);
    if ( file.exists() )
    {
    QMessageBox mBox;
    mBox.setWindowTitle( tr("File exists") );
    mBox.setIcon( QMessageBox::Question );
    mBox.setText( tr("Overwrite?") );
    mBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No );
        switch ( mBox.exec() )
        {
            case QMessageBox::Yes:
            break;

            default:
            delete schema;
            return;
            break;
        }
    file.open(QIODevice::WriteOnly);
    file.remove();
    }

QSqlDatabase db_sqlite = QSqlDatabase::addDatabase( QLatin1String("QSQLITE"), QLatin1String("lite") );
db_sqlite.setDatabaseName(path);
    if ( true != db_sqlite.open() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          db_sqlite.lastError().text() );
    QSqlDatabase::removeDatabase( QLatin1String("lite") );
    delete schema;
    return;
    }

QStringList create_queries = schema->sqlite_create_query();
    for ( int z = 0; z < create_queries.size(); z++ )
    {
    QSqlQuery schema_query(create_queries.at(z), db_sqlite);
        if ( true == schema_query.lastError().isValid() )
        {
        QMessageBox::warning( this,
                              QLatin1String("SQLITE Error"),
                              schema_query.lastError().text() );
        qApp->processEvents();
        schema_query.clear();
        QSqlDatabase::removeDatabase( QLatin1String("lite") );
        delete schema;
        return;
        }
    schema_query.clear();
    }

QSplashScreen * splash = new QSplashScreen( create_splash_image() );
splash->show();

blocking = 1;

unsigned int errors = 0;
unsigned int count_exported = 0;

QMap<int, QString> column_names = schema->column_names();
int columns_count = schema->columns_count();

// A000
QString s = QLatin1String("select * from ");
s.append(opened_album);
QSqlQuery query(s, db);
    while (query.next())
    {
    QString ins_q = QLatin1String("insert into a000(");

        for ( int x = 0; x < columns_count; x++ )
        {
        ins_q.append( column_names[x] );
            if ( x != ( columns_count - 1 ) )
            {
            ins_q.append( QLatin1String(",") );
            }
        }
    ins_q.append( QLatin1String(")") );
    ins_q.append( QLatin1String(" values (") );
        for ( int i = 0; i < columns_count; ++i )
        {
            if ( i == ( columns_count - 1 ) )
            {
            ins_q.append( process_value( i, query.value(i), false ) );
            }
            else
            {
            ins_q.append( process_value( i, query.value(i), true ) );
            }
        }
    ins_q.append( QLatin1String(")") );
    QSqlQuery insert_query(ins_q, db_sqlite);
        if ( true == insert_query.lastError().isValid() )
        {
        errors += 1;
        QMessageBox::warning( this,
                              tr("Database message"),
                              insert_query.lastError().text() );
        }
    insert_query.clear();
    count_exported += 1;
    QString message = tr("Exported");
    message.append( QLatin1String(" ") );
    message.append( QString::number(count_exported) );
    message.append( QLatin1String(" ") );
    message.append( tr("records") );
    splash->showMessage(message);
    qApp->processEvents();
    }

query.clear();

// A000_IMAGES
QString im_s = QLatin1String("select image_id,coin_id,file_name,saved_as,is_obv_icon,is_rev_icon,is_edge_icon from ");
im_s.append(opened_album);
im_s.append( QLatin1String("_images") );
QSqlQuery query_images(im_s, db);
    while ( query_images.next() )
    {
    bool image_id_ok = false;
    bool coin_id_ok = false;
    qint64 image_id = Q_INT64_C(-1);
    qint64 coin_id = Q_INT64_C(-1);
    image_id = query_images.value(0).toLongLong(&image_id_ok);
    coin_id = query_images.value(1).toLongLong(&coin_id_ok);

        if ( image_id_ok && coin_id_ok )
        {
        QString ins_im = QLatin1String("insert into a000_images");
        ins_im.append( QLatin1String("(") );
        ins_im.append( QLatin1String("image_id,coin_id,file_name,saved_as,is_obv_icon,is_rev_icon,is_edge_icon") );
        ins_im.append( QLatin1String(") values(") );
        ins_im.append( QString::number(image_id) );
        ins_im.append( QLatin1String(",") );
        ins_im.append( QString::number(coin_id) );
        ins_im.append( QLatin1String(",") );
        QString file_name = QLatin1String("");
        file_name = query_images.value(2).toString();
            if ( true != file_name.isEmpty() )
            {
            ins_im.append( QString(QChar(0x27)) );
            ins_im.append(file_name);
            ins_im.append( QString(QChar(0x27)) );
            }
            else
            {
            ins_im.append("null");
            }
        ins_im.append( QLatin1String(",") );
        QString saved_as = QLatin1String("");
        saved_as = query_images.value(3).toString();
            if ( true != saved_as.isEmpty() )
            {
            ins_im.append( QString(QChar(0x27)) );
            ins_im.append(saved_as);
            ins_im.append( QString(QChar(0x27)) );
            }
            else
            {
            ins_im.append("null");
            }
        ins_im.append( QLatin1String(",") );
        int int_obv_icon = 0;
        bool int_obv_ok = false;
        int_obv_icon = query_images.value(4).toInt(&int_obv_ok);
            if ( true == int_obv_ok )
            {
            ins_im.append( QString::number(int_obv_icon) );
            }
            else
            {
            ins_im.append("null");
            }
        ins_im.append( QLatin1String(",") );
        int int_rev_icon = 0;
        bool int_rev_ok = false;
        int_rev_icon = query_images.value(5).toInt(&int_rev_ok);
            if ( true == int_rev_ok )
            {
            ins_im.append( QString::number(int_rev_icon) );
            }
            else
            {
            ins_im.append("null");
            }
        ins_im.append( QLatin1String(",") );
        int int_edge_icon = 0;
        bool int_edge_ok = false;
        int_edge_icon = query_images.value(6).toInt(&int_edge_ok);
            if ( true == int_edge_ok )
            {
            ins_im.append( QString::number(int_edge_icon) );
            }
            else
            {
            ins_im.append("null");
            }
        ins_im.append( QLatin1String(")") );
        QSqlQuery insert_im_query(ins_im, db_sqlite);
            if ( true == insert_im_query.lastError().isValid() )
            {
            errors += 1;
            QMessageBox::critical( this,
                                   tr("Error"),
                                   insert_im_query.lastError().text() );
            }
        insert_im_query.clear();
        }
        else
        {
        continue;
        }
    }
query_images.clear();

// A000_IM_BLOBS
QString query_image_b = QLatin1String("select image_id,coin_id,image_b from ");
query_image_b.append(opened_album);
query_image_b.append( QLatin1String("_im_blobs") );
QSqlQuery query_iblobs(query_image_b, db);
    while ( query_iblobs.next() )
    {
    qint64 im_id = Q_INT64_C(-1);
    qint64 coin_id = Q_INT64_C(-1);
    bool im_id_ok = false;
    bool coin_id_ok = false;
    im_id = query_iblobs.value(0).toLongLong(&im_id_ok);
    coin_id = query_iblobs.value(1).toLongLong(&coin_id_ok);
        if ( im_id_ok && coin_id_ok )
        {
        QString ins_ib = QLatin1String("insert into ");
        ins_ib.append( QLatin1String("a000_im_blobs(image_id,coin_id,image_b) values (") );
        ins_ib.append( QString::number(im_id) );
        ins_ib.append( QLatin1String(",") );
        ins_ib.append( QString::number(coin_id) );
        ins_ib.append( QLatin1String(", :byte_array )") );

        QByteArray ba = query_iblobs.value(2).toByteArray();
        QSqlQuery ins_ib_query(db_sqlite);
        ins_ib_query.prepare(ins_ib);
            if ( ba.isNull() || ba.isEmpty() )
            {
            ins_ib_query.bindValue(":byte_array", QVariant( QString( QLatin1String("null") ) ) );
            }
            else
            {
            ins_ib_query.bindValue(":byte_array", QVariant(ba) );
            }

        bool ins_ib_ok = false;
        ins_ib_ok = ins_ib_query.exec();
            if (true != ins_ib_ok)
            {
            QMessageBox::critical(this,
                                 tr("Error"),
                                 tr("The database reported: %1").arg(ins_ib_query.lastError().text()) );
            }

        ins_ib_query.clear();
        }
        else
        {
        continue;
        }
    }
query_iblobs.clear();

// A000_DOCUMENTS
QString doc_s = QLatin1String("select doc_id,coin_id,file_name,saved_as from ");
doc_s.append(opened_album);
doc_s.append( QLatin1String("_documents") );
QSqlQuery query_documents(doc_s, db);
    while ( query_documents.next() )
    {
    bool doc_id_ok = false;
    bool coin_id_ok = false;
    qint64 doc_id = Q_INT64_C(-1);
    qint64 coin_id = Q_INT64_C(-1);
    doc_id = query_documents.value(0).toLongLong(&doc_id_ok);
    coin_id = query_documents.value(1).toLongLong(&coin_id_ok);

        if ( doc_id_ok && coin_id_ok )
        {
        QString ins_doc = QLatin1String("insert into a000_documents");
        ins_doc.append( QLatin1String("(") );
        ins_doc.append( QLatin1String("doc_id,coin_id,file_name,saved_as") );
        ins_doc.append( QLatin1String(") values(") );
        ins_doc.append( QString::number(doc_id) );
        ins_doc.append( QLatin1String(",") );
        ins_doc.append( QString::number(coin_id) );
        ins_doc.append( QLatin1String(",") );
        QString file_name = QLatin1String("");
        file_name = query_documents.value(2).toString();
            if ( true != file_name.isEmpty() )
            {
            ins_doc.append( QString(QChar(0x27)) );
            ins_doc.append(file_name);
            ins_doc.append( QString(QChar(0x27)) );
            }
            else
            {
            ins_doc.append("null");
            }
        ins_doc.append( QLatin1String(",") );
        QString saved_as = QLatin1String("");
        saved_as = query_documents.value(3).toString();
            if ( true != saved_as.isEmpty() )
            {
            ins_doc.append( QString(QChar(0x27)) );
            ins_doc.append(saved_as);
            ins_doc.append( QString(QChar(0x27)) );
            }
            else
            {
            ins_doc.append("null");
            }
        ins_doc.append( QLatin1String(")") );
        QSqlQuery insert_doc_query(ins_doc, db_sqlite);
            if ( true == insert_doc_query.lastError().isValid() )
            {
            errors += 1;
            QMessageBox::critical( this,
                                   tr("Error"),
                                   insert_doc_query.lastError().text() );
            }
        insert_doc_query.clear();
        }
        else
        {
        continue;
        }
    }
query_documents.clear();

// A000_DOC_BLOBS
QString query_doc_b = QLatin1String("select doc_id,coin_id,doc_b from ");
query_doc_b.append(opened_album);
query_doc_b.append( QLatin1String("_doc_blobs") );
QSqlQuery query_dblobs(query_doc_b, db);
    while ( query_dblobs.next() )
    {
    qint64 doc_id = Q_INT64_C(-1);
    qint64 coin_id = Q_INT64_C(-1);
    bool doc_id_ok = false;
    bool coin_id_ok = false;
    doc_id = query_dblobs.value(0).toLongLong(&doc_id_ok);
    coin_id = query_dblobs.value(1).toLongLong(&coin_id_ok);
        if ( doc_id_ok && coin_id_ok )
        {
        QString ins_db = QLatin1String("insert into ");
        ins_db.append( QLatin1String("a000_doc_blobs(doc_id,coin_id,doc_b) values (") );
        ins_db.append( QString::number(doc_id) );
        ins_db.append( QLatin1String(",") );
        ins_db.append( QString::number(coin_id) );
        ins_db.append( QLatin1String(", :byte_array )") );

        QByteArray ba = query_dblobs.value(2).toByteArray();
        QSqlQuery ins_db_query(db_sqlite);
        ins_db_query.prepare(ins_db);
            if ( ba.isNull() || ba.isEmpty() )
            {
            ins_db_query.bindValue(":byte_array", QVariant( QString( QLatin1String("null") ) ) );
            }
            else
            {
            ins_db_query.bindValue(":byte_array", QVariant(ba) );
            }

        bool ins_db_ok = false;
        ins_db_ok = ins_db_query.exec();
            if (true != ins_db_ok)
            {
            QMessageBox::critical(this,
                                 tr("Error"),
                                 tr("The database reported: %1").arg(ins_db_query.lastError().text()) );
            }

        ins_db_query.clear();
        }
        else
        {
        continue;
        }
    }
query_dblobs.clear();

// A000_DECS_BLOBS
QString query_desc_b = QLatin1String("select coin_id,desc_b from ");
query_desc_b.append(opened_album);
query_desc_b.append( QLatin1String("_desc_blobs") );
QSqlQuery query_descblobs(query_desc_b, db);
    while ( query_descblobs.next() )
    {
    qint64 coin_id = Q_INT64_C(-1);
    bool coin_id_ok = false;
    coin_id = query_descblobs.value(0).toLongLong(&coin_id_ok);
        if ( coin_id_ok )
        {
        QString ins_desc = QLatin1String("insert into ");
        ins_desc.append( QLatin1String("a000_desc_blobs(coin_id,desc_b) values (") );
        ins_desc.append( QString::number(coin_id) );
        ins_desc.append( QLatin1String(", :byte_array )") );

        QByteArray ba = query_descblobs.value(1).toByteArray();
        QSqlQuery ins_desc_query(db_sqlite);
        ins_desc_query.prepare(ins_desc);
            if ( ba.isNull() || ba.isEmpty() )
            {
            ins_desc_query.bindValue(":byte_array", QVariant( QString( QLatin1String("null") ) ) );
            }
            else
            {
            ins_desc_query.bindValue(":byte_array", QVariant(ba) );
            }

        bool ins_desc_ok = false;
        ins_desc_ok = ins_desc_query.exec();
            if (true != ins_desc_ok)
            {
            QMessageBox::critical(this,
                                 tr("Error"),
                                 tr("The database reported: %1").arg(ins_desc_query.lastError().text()) );
            }

        ins_desc_query.clear();
        }
        else
        {
        continue;
        }
    }
query_descblobs.clear();

    if ( true == db_sqlite.isOpen() )
    {
    db_sqlite.close();
    }

blocking = 0;
qApp->processEvents();

QSqlDatabase::removeDatabase( QLatin1String("lite") );

splash->close();
delete splash;

    if ( errors > 0 )
    {
    QMessageBox::warning( this,
                          QLatin1String("Number of INSERT errors "),
                          QString::number(errors) );
    }
}

void MainWindow::save_downloaded( QByteArray ba, QString p )
{
bool success = write_byte_array(p, ba);

    if ( true != success )
    {
    QMessageBox::critical(this,
                          tr("Error"),
                          tr("Could not save image.") );
    }
}

void MainWindow::copy_downloaded( QByteArray ba )
{
QImage image;

bool blob_loaded = image.loadFromData(ba);

    if (true == blob_loaded)
    {
    QMimeData * data = new QMimeData;
    data->setImageData(image);
    QClipboard * clipboard = QApplication::clipboard();
    clipboard->setMimeData(data, QClipboard::Clipboard);
    statusBar()->showMessage( tr("Image is copied to clipboard."), 5000 );
    }
    else
    {
    QMessageBox::warning( this,
                          tr("Warning"),
                          tr("Failed to load image.") );
    }
}

void MainWindow::show_downloaded( QByteArray ba )
{
QPixmap pixmap;

bool blob_loaded = pixmap.loadFromData(ba);

    if (true == blob_loaded)
    {
    GraphicsView * view = new GraphicsView( 0,
                                            gl_tested,
                                            max_size);
    view->set_image(pixmap);
    view->show();
    QObject::connect( view,
                      SIGNAL( return_gl_tested(bool, int) ),
                      this,
                      SLOT( update_gl_tested(bool, int) ) );
    }
    else
    {
    QMessageBox::warning( this,
                          tr("Warning"),
                          tr("Failed to load image.") );
    }
}

void MainWindow::get_download( Download * d,
                               bool ok,
                               QString s,
                               QString p,
                               QString e )
{
    if ( true == ok ) 
    {
    QByteArray ba = QByteArray( d->return_data() );
    d->close();
        if ( s == QString ( QLatin1String("show") ) )
        {
        show_downloaded(ba);
        }
        else if ( s == QString ( QLatin1String("copy") ) )
        {
        copy_downloaded(ba);
        }
        else if ( s == QString ( QLatin1String("save") ) )
        {
        save_downloaded(ba, p);
        }
    }
    else
    {
    d->close();
    QMessageBox::information( this,
                              tr("HTTP"),
                              tr("Download failed: %1.").arg(e) );
    }
}
